What's the efficient way to find prime

kindly suggest way to find prime number efficiently

Precompute the prime numbers using sieve technique.

In the sieve technique where you create a boolean array of 1000005 size.

And start from the first prime number i.e. 2. Take its square(4) and increment it by the number you took (i.e. 4,6,8,10 and so on). Mark all these as false since they cannot be primes.

Now take the next unmarked number, 3. And mark 9,12,15 and so as false. Similarly do it for 4. 16,20,24 and so on as false.

When you finish the loop, count the number of primes within the range.

Further explained:

In the image below, say we have to get all primes between 1-100. First outside the loop mark 1 as not a prime number (in case of boolean array as true or in int array as 1).
Now enter a for loop:
find the index which has set value as 0. initially it will be 2.
Start another for loop and mark all the numbers which are divisible by 2 and are greater than or equal to the square of it as true/1 (not primes). these numbers will be 4,6,8,10 and so on.
Now the next number will be 3. these numbers will be 9,12,15 and so on.
Similarly do it till 10 if total numbers are 100.

After this do a simple traversal to store all the prime numbers. Refer to the image below for a visualization

image

you can see this video to understand the basic logic
https://www.youtube.com/watch?v=8sniiDbfPK4

Day 6 - Prime Visits | Pre-computing Primes using Sieve | Competitive…

if it solves your doubt, please mark it as resolved