Today, I saw an article about various algorithms that print prime numbers, and I was surprised to realize the implementation of its better algorithm in the LINQ version.
The reference algorithm is as follows.
1. initialize the following list.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
2. Extract the first number (2) and remove all the numbers that can be divisible by 2.
2 3 5 7 9 11 13 15 17 19 21 23 25 27 29
3. Take the second number (3) and remove all numbers that can be divisible by 3.
2 3 5 7 11 13 17 19 23 25 29
4. Take the third number (5), because 4 has been removed, and then remove all the numbers that can be divisible by 5.
2 3 5 7 11 13 17 19 23 29
The next number is 7, but the square of 7 is 49, which is greater than 30, so we can stop the calculation. The remaining number is all the prime numbers.
Static void main (string [] ARGs) {int length = 30; // maximum length var list = enumerable. range (1, length); // a sequence of 1-{maximum length} For (INT I = 1; I ++) {int n = List. elementat (I); // take the next valid number if (N * n> length) // If the square of the number is greater than {maximum length}, {break ;} list = List. where (P => P = n | P % N! = 0);} // print foreach (VAR item in list) {console. writeline (item );}}