Java Reference
In-Depth Information
L ISTING 22.5
PrimeNumbers.java
1 import java.util.Scanner;
2
3 public class PrimeNumbers {
4 public static void main(String[] args) {
5 Scanner input = new Scanner(System.in);
6 System.out.print( "Find all prime numbers <= n, enter n: " );
7
int n = input.nextInt();
8
9
final int NUMBER_PER_LINE = 10 ; // Display 10 per line
10
int count = 0 ; // Count the number of prime numbers
11
int number = 2 ; // A number to be tested for primeness
12
13 System.out.println( "The prime numbers are:" );
14
15
// Repeatedly find prime numbers
16
while (number <= n) {
17
// Assume the number is prime
18
boolean isPrime = true ; // Is the current number prime?
19
20 // Test if number is prime
21 for ( int divisor = 2 ; divisor <= ( int )(Math.sqrt(number));
22 divisor++) {
23 if (number % divisor == 0 ) { // If true, number is not prime
24 isPrime = false ; // Set isPrime to false
25
check prime
break ; // Exit the for loop
26 }
27 }
28
29
// Print the prime number and increase the count
30
if (isPrime) {
increase count
31
count++; // Increase the count
32
33 if (count % NUMBER_PER_LINE == 0 ) {
34 // Print the number and advance to the new line
35 System.out.printf( "%7d\n" , number);
36 }
37 else
38 System.out.printf( "%7d" , number);
39 }
40
41
// Check if the next number is prime
check next number
42
number++;
43 }
44
45 System.out.println( "\n" + count +
46
" prime(s) less than or equal to " + n);
47 }
48 }
Find all prime numbers <= n, enter n: 1000
The prime numbers are:
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
...
...
168 prime(s) less than or equal to 1000
 
 
Search WWH ::




Custom Search