The following two C++ programs give the same result, but when I benchmarked them for a very high figure (something like in millions), the difference was too much, the second program was very efficient.
There difference is in the nested loop, in the first one it's int j=2; j<i; j++ and in the second one it's int j=2; j*j<i; j++
Program # 1:
#include <iostream>
using namespace std;
int main () {
for (int i=200; i<400; i++) {
bool prime=true;
for (int j=2; j<i; j++) {
if (i % j == 0) {
prime=false;
break;
}
}
if(prime == true){ cout << i << "\n"; }
}
return 0;
}
Program # 2
#include <iostream>
using namespace std;
int main () {
for (int i=200; i<400; i++) {
bool prime=true;
for (int j=2; j*j<i; j++) {
if (i % j == 0) {
prime=false;
break;
}
}
if(prime == true){ cout << i << "\n"; }
}
return 0;
}
Think of it like this:
If N is not prime, then there is a tuple (p, q) | 2 <= p < N & 2 <= q < N.
p <= q when we begin testing. Each iteration of the loop we increment p by 1. As a result, q necessarily has to decrease, because N/p = q.
When p > q during the iteration process, then for each iteration there and after, the only whole numbers q can be -- if N is not prime -- have already been tested, so we would be doing double the work for no reason, thus we stop at that point.
Disclaimer: My ability to speak mathematics has diminished over the years, so I might not be as clear or concise as I could be. For this I apologize, but I hope it helped.
sublime text - compare side-by-side.
packagecontrol.io/packages/Compare%20Side-By-Side
Perfect for this stuff.
j
stuff ;)
programm 2: (int j=2; j*j<i; j++) checks if i is bigger than the j² programm 1: (int j=2; j<i; j++) checks if i is bigger than j that's the difference, I would have to check the equation by hand to see the difference ;D since I don't have a good formal mathematical education :)