There are various methods through which we can calculate prime numbers upto n.
1) General Method
In this method, we usually run two for loops in which the First one is used to increase the number and the second one is used to check whether the number is prime or not. Second loop runs from 2 to ( n / 2 + 1 ) ( for better performance).
Note: This is the least efficient method (one should not use this if efficiency is required.)
2) Square-Root Method
In this method, two loops run first one is to increase the number and the second one is to check whether the number is prime or not. The second loop runs from 2 to square root (number) (a number which is to be check), that’s why the run length of second for loop is relatively small, that’s why it’s efficient than the naïve approach.
3) Sieve of Eratosthenes
This is the best and most efficient method to calculate the prime numbers upto n.
Algorithm for Sieve of Eratosthenes:
Set all the values to True (we are considering every number to be Prime)
Mark all the multiples of p as False and increase the value of p to the next prime number
At the end of both the for loops, all the values that are marked as TRUE are primes and all the composite numbers are marked as FALSE in step 3.
Time complexity : O(n*log(log(n)))
Note: Performance of General Method and SquareRoot Method can be increased a little bit if we check only ODD numbers because instead of 2 no even number is prime.
Example:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer