[Java] Eratosthenes sieve method for verifying prime numbers

Source: Internet
Author: User

The Eratosthenes sieve method, called the sieve or the AI sieve, is a simple algorithm for the prime number of the Eratosthenes proposed by the Greek mathematician. To get the full number of prime numbers within the natural n, the multiples of all primes of the root n must be removed, and the remainder is prime.


In order to get the total number of prime numbers within N, it is necessary to remove the multiples of all primes, and the remainder is prime. Give the range N of the value to be sifted to find the prime number within. First use 2 to sift, that is, 2 left, the number of 2 is removed, and then the next prime number, that is, 3 sieve, 3 left, the multiples of 3 is removed, then the next prime number 5 sieve, 5 left, the multiples of 5 are removed;

Java source code:

Package Test1.number;public class Eratosthenes {public static void main (string[] args) {int max = $; try {max = INTEGER.P Arseint (Args[0]);} catch (Exception e) {} boolean[] IsPrime = new Boolean[max + 1];for (int i = 0; I <= max; i++) isprime[i] = True;isprime [0] = isprime[1] = false;int n = (int) Math.ceil (MATH.SQRT (max)); for (int i = 0; I <= N, i++) {if (Isprime[i]) for (int j = 2 * i; j <= Max; j = j + i) isprime[j] = false;} int Largest;for (largest = max;!isprime[largest]; largest--); System.out.println ("the largest prime less than or equal to" + max+ "is" + largest);}}

Operation Result:


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Java] Eratosthenes sieve method for verifying prime numbers

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.