FindPrimes - if (n < 2) return false; /* if n is even,...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
/* * File: FindPrimes.java * --------------------- * This program finds all prime numbers between the constants * LOWER_BOUND and UPPER_BOUND. * * Author: CS1MD3, Oct. 2008 */ import acm.program.*; i public class FindPrimes extends ConsoleProgram { p 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) {
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 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; }...
View Full Document

This note was uploaded on 10/27/2009 for the course COMP SCI 1MD3 taught by Professor Various during the Winter '07 term at McMaster University.

Ask a homework question - tutors are online