/* * File: FindPrimes.java * --------------------- * This program finds all prime numbers between the constants * LOWER_BOUND and UPPER_BOUND. * * Author: CS1MD3, Oct. 2008 */ import acm.program.*; public class FindPrimes extends ConsoleProgram { public void run() { for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) { if (isPrime(i)) println(i); } } /* Returns true if *n* is a prime number */ private boolean isPrime(int n) { if (n < 2) return false; /* if n is even, only 2 is a prime */ if (n % 2 == 0) return (n == 2); /* when n >2 and odd */ int limit = (int) Math.round(Math.sqrt(n)); for (int i = 3; i <= limit; i += 2) { if (n % i == 0) return false; } return true; } /* Lower and upper bound constants */ private static final int LOWER_BOUND = 1; private static final int UPPER_BOUND = 1000; }