TCS Coding Practice Question | Checking Prime Number
Given a number N, the task is to check if N is a Prime Number or not using Command Line Arguments.
Input: N = 7 Output: Yes Input: N = 15 Output: No
- 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.
- In C:
- In Java:
Time Complexity: O(N)
Auxiliary Space: O(1)
My Personal Notes arrow_drop_up
Please Login to comment...