Java using filtering to find an example of prime numbers within N (Java prime) _java

Source: Internet
Author: User

Copy Code code as follows:

/**
* @author Jxqlovedn
* Eratosthenes prime number Screening method, please refer to: http://zh.wikipedia.org/zh-cn/Eratosthenes Sieve method
*/
public class Aratosternyalgorithm {

public static void Getprimes (int n) {
if (N < 2 | | | n > 1000000) The maximum value is limited to 1 million because of the JVM memory limit, there are other flexible schemes that can be bypassed (e.g. bitmap method)
throw new IllegalArgumentException ("Input parameter n Error!") ");

int[] array = new Int[n]; Assuming that all the initial numbers are prime, and a number is a prime, the value is 0; For example, the first number is prime then array[0] is 0
Array[0] = 1; 0 is not prime
ARRAY[1] = 1; 1 is not prime
The following is the filtering core process
for (int i = 2; i < MATH.SQRT (n); i++) {//starting from the minimum prime number 2
if (array[i] = = 0) {
for (int j = I*i J < n; j + = i) {
ARRAY[J] = 1; Identifies the location as a non prime
}
}
}

Print all prime numbers within N, 10 outputs per row
SYSTEM.OUT.PRINTLN (n + ") within the prime number as follows:";
int count = 0; Number of prime numbers that are currently being exported
int rowlength = 10; Number of primes per line output
for (int i = 0; i < Array.Length; i++) {
if (array[i] = = 0) {
if (count% rowlength = 0 && count!= 0) {
System.out.println ();
}
count++;

System.out.print (i + "t");
}
}
}

public static void Main (string[] args) {
Getprimes (99999);
}
}

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.