Java Reference
In-Depth Information
18 if (count % NUMBER_OF_PRIMES_PER_LINE == 0 ) {
19 // Print the number and advance to the new line
20 System.out.printf( "%-5s\n" , number);
21 }
22 else
23 System.out.printf( "%-5s" , number);
24 }
25
26 // Check whether the next number is prime
27 number++;
28 }
29 }
30
31
/** Check whether number is prime */
32
33
public static boolean isPrime( int number) {
isPrime method
for ( int divisor = 2 ; divisor <= number / 2 ; divisor++) {
34
if (number % divisor == 0 ) { // If true, number is not prime
35
return false ; // Number is not a prime
36 }
37 }
38
39
return true ; // Number is prime
40 }
41 }
The first 50 prime numbers are
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
We divided a large problem into two subproblems: determining whether a number is a prime
and printing the prime numbers. As a result, the new program is easier to read and easier to
debug. Moreover, the methods printPrimeNumbers and isPrime can be reused by other
programs.
5.7 Case Study: Converting Decimals to Hexadecimals
This section presents a program that converts a decimal number to a hexadecimal
number.
Key
Point
Hexadecimals are often used in computer systems programming (see Appendix F for an intro-
duction to number systems). To convert a decimal number d to a hexadecimal number is to
find the hexadecimal digits
h n , h n - 1 , h n - 2 ,
, h 2 , h 1 ,
and
h 0
such that
c
16 n
16 n - 1
16 n - 2
d
=
h n *
+
h n - 1 *
+
h n - 2 *
+ c
16 2
16 1
16 0
+
h 2 *
+
h 1 *
+
h 0 *
These hexadecimal digits can be found by successively dividing d by 16 until the quotient is
0. The remainders are and The hexadecimal digits include the
decimal digits 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9, plus A, which is the decimal value 10; B, which is
the decimal value 11; C, which is 12; D, which is 13; E, which is 14; and F, which is 15.
h 0 , h 1 , h 2 ,
, h n - 2 , h n - 1 ,
h n .
c
 
 
 
Search WWH ::




Custom Search