Pages

Friday, 19 August 2016

Chapter 6 Exercise 10, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

6.10 (Use the isPrime Method) Listing 6.7, PrimeNumberMethod.java, provides the isPrime(int number) method for testing whether a number is prime. Use this method to find the number of prime numbers less than 10000.



public class ProgrammingExercise6_10 {
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int numberOfPrime = 0;
  for (int i = 0; i < 10000; i++) {
 
   if (isPrime(i + 1)) {
    System.out.print((i + 1) + " ");
    numberOfPrime++;
    if (numberOfPrime % 10 == 0) {
     System.out.println();
    }
   }
 
  }
 
  System.out.println("The number of primes is " + numberOfPrime);
 
 }
 
 /** Check whether number is prime */
 public static boolean isPrime(int number) {
  for (int divisor = 2; divisor <= number / 2; divisor++) {
   if (number % divisor == 0) { // If true, number is not prime
    return false; // number is not a prime
   }
  }
 
  return true; // number is prime
 }
 
}

No comments:

Post a Comment