Home > Back-end >  Questions about for prime Numbers
Questions about for prime Numbers

Time:10-05

Middle step is I==j + 1
What do you mean?

CodePudding user response:

J cycle when the last time, will arrive at I==j + 1, can go to here, that is the prime, I or midway'll break

Actually there is no need to put in j loop judgment, in j loop, I loop in good
The
For (I=1; i<=lim; I++) {
For (j=2; jIf (I % j==0) break;
}
If (I==j) a [MAX++]=I;//judgment on the outside to
}

CodePudding user response:

The second for loop if run smoothly, only from 2 to I - 1, "I % j==0" when, "I=j + 1" will be established, that is to say at this point, I was a prime number, therefore return the MAX value is less than or equal to the value of the lim of prime Numbers in the minus one, because 2 is also a prime number, but the code in the for loop will exclude 2

CodePudding user response:

Is after I=j + 1 time don't need to decide, can we determine the prime Numbers, but I think to recognize I upward integer is the square root of arithmetic.

CodePudding user response:

When I==j + 1 set up?
Only when j is I - 1, this equation is set up
Despite I % j ahead!=0, but this I==j - 1 is not formed
Therefore, only when j=I - 1, namely the for (j) the cycle running to the last time, and I % j==0 is not established, then can let I==founded j - 1
Any such instructions, from 2 to I - 1 a factor is not I, so, I must be the prime number


This code efficiency is very low, there are a lot of places can optimize
However, the most important to a problem, the algorithm 2 is also a prime number this situation to missed
Aa array is calculated, and does not contain the prime number 2, 2 is the smallest prime

This function is less than or equal to all the prime Numbers lim, and on the aa arrays, and returns the number of primes
Because of the lack of prime number 2, this function is wrong
  • Related