Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3
https://code.sololearn.com/ceSniyF43n49/?ref=app This is a pretty fast implementation in Python (not the fastest but very fast). Shouldn't be that hard to transfer to c++.
28th Sep 2019, 7:57 AM
Thoq!
Thoq! - avatar
+ 2
Honestly I don't know much about prime number algorithms and with concept is the fastest but this seems inefficient to me: if(Prime_Num % 2 == int{}) isPrime = false; First of all, why don't you just use if (Prime_Num % 2 == 0) ?? Second why you use this comparison that never changes in a for loop? This is a waste of CPU resources to compare it over and over again though the result can't change. If the number was even you don't need to loop anymore so that's even more inefficient.
28th Sep 2019, 6:27 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 2
The prime number checking part is the bottleneck here. In your code you first find all odd numbers in the range of 2 to 2^14-1 and then check if your prime number is a multiple of any two odd numbers. This is a quadratic operation (nested loop) and can be extremely slow. The condition to check if the prime number is divisible by 2 is checked repeatedly and can be moved outside the loop. Also if is_prime is false, then the odd multiple checking loop should not be executed. Also, your code does not work for 2, which is a prime number. A better way to check for a number being prime is to just check if it has any factors. For that, you can run a loop with i from 2 to the number and just check if Prime_Num % i is 0. If it is, your number is not prime. This is a linear operation which is faster. Also, the loop's upper limit can be reduced to the square root of the number (sqrt(Prime_Num)) for even faster results. Also, note that std::ios_base::sync_with_stdio serves no purpose when you don't use C++ I/O.
28th Sep 2019, 6:53 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar