Friday, 20 January 2017

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

22.10 (Number of prime numbers) Programming Exercise 22.8 stores the prime numbers in a file named PrimeNumbers.dat. Write a program that finds the num-
ber of prime numbers that are less than or equal to 10 , 100 , 1,000 , 10,000 ,
100,000 , 1,000,000 , 10,000,000 , 100,000,000 , 1,000,000,000 , and
10,000,000,000 . Your program should read the data from PrimeNumbers.dat.


import java.io.*;

public class Exercise10 {

 public static void main(String[] args) throws IOException {
  DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream("PrimeNumbers.dat")));
  long result = 0;
  for (long i = 10; i <= 10000000000L; i *= 10) {
   long number = 0;
   try {
    while((number = input.readLong()) < i)
     result++;
    System.out.println(i + " - " + result);
    result++;
   } catch (EOFException e) {
    System.out.println(number + " - " + result);
    break;
   }

  }
  input.close();   
 }
}

No comments :

Post a Comment