VOOZH about

URL: https://www.geeksforgeeks.org/interview-experiences/tcs-coding-practice-question-prime-numbers-upto-n/

⇱ TCS Coding Practice Question | Prime Numbers upto N - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

TCS Coding Practice Question | Prime Numbers upto N

Last Updated : 11 Jul, 2025

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:

Output:

  • In C: 
     

👁 Image

 

  • In Java: 
     

👁 Image


 

Time Complexity: O(N*N)
Auxiliary Space: O(1)

Comment