![]() |
VOOZH | about |
Write a program to print the first 10 prime numbers.
Note: A number N is said to be prime if it has exactly two factors i.e. 1 and the number itself N
:
2, 3, 5, 7, 9...
Approach:
Prime Test: To check whether a number N is prime we can check its divisibility with each number from 2 to N - 1, If it is divisible by any number in this range, we can conclude that N is not a prime number.
Looping until first 10 primes are not found: We can use a while loop to continue our prime check on the numbers until we print the first 10 prime numbers.
Step-by-step algorithm:
Below is the implementation of the above approach:
2 3 5 7 11 13 17 19 23 29
Time Complexity: O(1) if we consider only fixed number of elements like 10. If number of elements are provided by the user, then it would be O(N^2) and can be optimized using Sieve Algorithm
Auxiliary Space: O(1)