How to avoid optimize my code
I'm getting TLE in one test case
You are supposed to use the prime seive optimisation technique. Also make sure that you call the primeseive function that you will make before the test cases only to prevent TLE.
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.
What is the logic of seive optimisation technique
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
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
