C # search for prime numbers

Source: Internet
Author: User

I have learned some methods to search for prime numbers before I learned C. The conventional method seems to be inefficient. Recently I found a "delete method" on the Forum to search for prime numbers, the space complexity is much lower, with less repeated execution, but no execution steps required. It is a class about searching for prime numbers from 0 to n. It starts from 1.1 drops of programming.

Class prime
  
{
  
Public static int [] primelist;
  
Public static void findprime (int n)
  
{
  
Int [] intlist;
  
Intlist = new int [N];
  
For (int p = 2; P <= N; P ++) intlist [P-1] = P; // assign 2 to n to this array
  
For (int p = 2; P <math. SQRT (n); P ++)
  
{
  
Int J = p + 1;
  
While (j <= N)
  
{
  
If (intlist [J-1]! = 0) & (intlist [J-1] % P) = 0) intlist [J-1] = 0; // determine if the element is not a prime number and assign the value to zero
  
J = J + 1;
  
}
  
}
  
Int I = 0;
  
For (int p = 2; P <= N; P ++)
  
{
  
If (intlist [P-1]! = 0)

I = I + 1; // we can see that all elements that are not prime numbers are assigned 0; the number of elements that are not 0 is counted, that is, the number of prime numbers from 0 to n.
  
}
  
Primelist = new int [I]; // creates an array to store prime numbers.
  
I = 0;
  
For (int p = 2; P <= N; P ++)
  
{
  
If (intlist [P-1]! = 0) // so far, the element not zero in the array is a prime number,
  
{
  
Primelist [I] = intlist [P-1]; // store the prime number in the array.
  
I = I + 1;
  
}
  
}
  
}
  
}

The so-called deletion method is to assign a number to zero if it is determined that it is not a prime number during the test. It can also be understood as indirect search for prime numbers, which is easier than direct search.

Learning Programming starts from 1.1 drops ..

Related Article

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.