TCS Coding Practice Question | Prime Numbers upto N
Given a number N, the task is to find the Prime Numbers from 1 to N using Command Line Arguments.
Examples:
Input: N = 7
Output: 2, 3, 5, 7
Input: N = 13
Output: 2, 3, 5, 7, 11, 13
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, using a variable say i, to check if they are prime or not. This is done as follows:
In each iteration,
- Check if any numbers from 2 to (i/2+1) divide i completely (i.e. if it is a factor of i).
- If yes, then i is not a prime number. Hence check for next number
- If no, then i is a prime number. Hence print the value of i and check for next number
- After the loop has ended, the prime numbers from 1 to N are printed on the screen.
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;
}
void findPrimes( int n)
{
int i;
for (i = 2; i <= n; i++) {
if (isPrime(i) == 1)
printf ( "%d, " , i);
}
printf ( "\n" );
}
int main( int argc, char * argv[])
{
int n;
if (argc == 1)
printf ( "No command line arguments found.\n" );
else {
n = atoi (argv[1]);
findPrimes(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 findPrimes( int n)
{
int i;
for (i = 2 ; i <= n; i++) {
if (isPrime(i) == 1 )
System.out.print(i + ", " );
}
System.out.println();
}
public static void main(String[] args)
{
if (args.length > 0 ) {
int n = Integer.parseInt(args[ 0 ]);
findPrimes(n);
}
else
System.out.println( "No command line "
+ "arguments found." );
}
}
|
Output:
Time Complexity: O(N*N)
Auxiliary Space: O(1)
Last Updated :
11 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...