In the written test questions, the probability of finding a prime number is relatively high. I did it yesterday. It is not very difficult, but I can examine the programmer's mathematical and coding skills.
It is ideal to use nested loops. How can we reduce the number of loops? How can we find all prime numbers smaller than N?
It is impossible to divide a number with all numbers smaller than it. Just check the square root of N. However, there is still a precision issue when the root number is used directly. This may cause errors.
Simply write the judgment condition as I * I <= N. The truth is that I is more than the square root of N, before checking the first I divisor N, You can first check whether N can be divisible if it is smaller than the second I.
The following calculate the prime number:
[] FindPrime ([] prime = [max + 1 = (j = 2; j * j <= max; j ++ (k = 2 * j; k <= max; k ++ (k % j = 0 prime [k] = 1 (I = 2; I <max; I ++ (prime [I] = 0 [] p = (I = 0; I <list. size (); I ++ = [] prime = Prime. findPrime (1000 (I = 0; I <prime. length; I ++ ""