Used prime sieve method but still one of the test case case is failing, please guide
Hello,
Your logic for sieve method is somewhat wrong.
Following is the modification:
for (int i=3;i*i<=N;i+=2)
{
if(p[i]){
for(int j=i*i;j<=N;j+=i)
{
p[j]=0;
}
}
}
Hope, this would help.
Give a like, if you are satisfied.
There is a video on optimization of sieve method in the course, which i used and it works perfectly.
But i am not able to identify which case is failing and why
Correcting myself, your code is correct.
But it is giving run time error on one test case.
Runtime error can occur due to following reasons:
- Invalid memory access during run-time.
- Accessing linked list nodes that do not exist.
- Dividing by zero.
- Large allocation of memory together/Large Static Memory Allocation.
- Making a silly mistake.
In your case it’s silly mistake,
In the inner loop iterating on values of j, you are assigning value ii.
The value of ii can also be larger than the range of int.
Thus, j being a variable of int datatype, is incapable of storing it.
Hence, it is resulting in run error.
Hope, i have cleared your doubt.
Give a like, if you are satisfied.
Okay so now i have changed the datatype of j to long long int and other variables to int. Still it’s showing run error.
You have make i also long.
This is because, when you multiply two integers i.e. i*i, the result will also be an integer irrespective of it’s actual value.
So, there is no meaning of stroing the result in long j.
So, implicitly the result of multiplication is converting into integer if it’s value is out of the range of int.
Hope, this would help.
Give a like, if you are satisfied.
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.