Print the quality of the LINQ Algorithm

Source: Internet
Author: User

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 );}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.