C++ Prime number task from the book -
I'm starting a C ++;) Find all the major numbers between the code below 2-1000 How cool is the way:
int i, j; For {I = 2; i & lt; 1000; i ++} {for (j = 2; j & lt; = (i / j); j ++) {if (! (I% j)) break ; If (h & gt; (i / j)) cout & lt; & Lt; I & lt; & Lt; "Prime \ n"; }}
You stop when j = i have to stop a first simple optimization when J = sqrt (i) (because there can be no greater number of factors than its square root).
A very fast implementation is for example.
Edit: The code looks something mysterious, so here's how it works:
The ending condition for the internal i / J , j j == i , then we have i / j == 0 and Will break for.
Next check if (j & gt; (i / j)) is really bad; in fact it only checks whether the position of the end of the loop is killed (hence our If we hit for the end, then j == i + 1 (think about it) => i / J == 0 => This is a key if we hit a break, then it means j is a component of i , but not just anyone Also factor, really smallest (Because we first j which breaks i ! Since j is the smallest factor, other factors (or i / j Product of remaining factors given by ) will be equal to or equal to j , so test if j & lt; = i / j , we hit a brake and i is the smallest factor.
This is something unreadable code!
Comments
Post a Comment