Given a number N, the task is to check if N is a Prime Number or not using Command Line Arguments.
Examples:
Input: N = 7
Output: Yes
Input: N = 15
Output: No
Approach:
- Since the number is entered as Command line Argument, there is no need for a dedicated input line
- Extract the input number from the command line argument
- This extracted number will be in String type.
- Convert this number into integer type and store it in a variable, say N
- Now loop through the numbers from 2 to N/2+1, using a variable say i.
In each iteration,
- Check if i divide N completely (i.e. if it is a factor of N).
- If yes, then N is not a prime number.
- If no, then N is a prime number.
- After the loop has ended, it is found out that N is prime or not.
Note: Please note that 1 is not checked in this scenarios because 1 is neither prime nor composite.
Program:
C
#include <stdio.h>
#include <stdlib.h> /* atoi */
int isPrime( int x)
{
int i;
for (i = 2; i < x / 2 + 1; i++) {
if (x % i == 0) {
return 0;
}
}
return 1;
}
int main( int argc, char * argv[])
{
int n;
if (argc == 1)
printf ( "No command line arguments found.\n" );
else {
n = atoi (argv[1]);
if (isPrime(n) == 1)
printf ( "Yes\n" );
else
printf ( "No\n" );
}
return 0;
}
|
Java
class GFG {
public static int isPrime( int x)
{
int i;
for (i = 2 ; i < x / 2 + 1 ; i++) {
if (x % i == 0 ) {
return 0 ;
}
}
return 1 ;
}
public static void main(String[] args)
{
if (args.length > 0 ) {
int n = Integer.parseInt(args[ 0 ]);
if (isPrime(n) == 1 )
System.out.println( "Yes" );
else
System.out.println( "No" );
}
else
System.out.println( "No command line "
+ "arguments found." );
}
}
|
Python3
import sys
def is_prime(number):
if number < = 1 :
return False
sqrt_number = int (number * * 0.5 )
for i in range ( 2 , sqrt_number + 1 ):
if number % i = = 0 :
return False
return True
if __name__ = = "__main__" :
if len (sys.argv) ! = 2 :
print ( "Usage: python prime_check.py <number>" )
sys.exit( 1 )
number = int (sys.argv[ 1 ])
if is_prime(number):
print (number, "is prime." )
else :
print (number, "is not prime." )
|
Output:



Time Complexity: O(N)
Auxiliary Space: O(1)
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
05 Sep, 2023
Like Article
Save Article