Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class PrimeSieveOfEratosthenes {
- /**
- * Program: PrimeSieveOfEratosthenes.java
- * Purpose: Find all primes up to a number using Eratosthenes' Sieve.
- * Creator: Chris Clarke, author of books "50 Java Program Source Codes"
- and "50 More Java Source Codes".
- Each contains brand new material.
- Available now in e-book and paperback.
- * Created: 21.03.2014
- */
- public static void main(String[] args) {
- int number = 0;
- if (args.length>0) {
- try {
- number = Integer.parseInt(args[0]);
- runSieve(number);
- } catch (NumberFormatException e) {
- System.out.println("That\'s not an integer!");
- } // end try/catch
- } else {
- Scanner scan = new Scanner(System.in);
- System.out.print("Enter a number between 1 & 100: ");
- number = scan.nextInt();
- runSieve(number);
- } // end if
- } // end main()
- public static void runSieve(int upperBound) {
- int sqrt = (int) Math.sqrt(upperBound); // square root
- // boolean array of non-primes, to begin with they're all false
- boolean[] isComposite = new boolean[upperBound + 1];
- // find primes up to square root of upper bound
- for (int m = 2; m <= sqrt; m++) {
- if (!isComposite[m]) { // if prime
- // print prime number
- System.out.print(m + " ");
- // mark every multiple of m as non-prime
- for (int k = m * 2; k <= upperBound; k += m) {
- // mark as not prime
- isComposite[k] = true;
- }//end for k
- }//end if
- }//end for m
- for (int m = sqrt+1; m <= upperBound; m++) {
- if (!isComposite[m]) { // if prime
- // print prime number
- System.out.print(m + " ");
- }//end if
- }//end for m
- }//end runSieve()
- }//end class PrimeSieveOfEratosthenes
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement