Java Reference
In-Depth Information
15 System.out.println(
"The greatest common divisor for "
+ n1 +
16
gcd(n1, n2)
invoke
gcd
" and "
+ n2 +
" is "
+
);
17 }
18
19
/** Return the gcd of two integers */
public static int
gcd(
int
n1,
int
n2) {
compute gcd
20
21
int
gcd =
1
;
// Initial gcd is 1
22
int
k =
2
;
// Possible gcd
23
24
while
(k <= n1 && k <= n2) {
25
if
(n1 % k ==
0
&& n2 % k ==
0
)
26 gcd = k;
// Update gcd
27 k++;
28 }
29
30
return
gcd;
return gcd
// Return gcd
31 }
32 }
Enter first integer:
Enter second integer:
The greatest common divisor for 45 and 75 is 15
45
75
By encapsulating the code for obtaining the gcd in a method, this program has several
advantages:
1. It isolates the problem for computing the gcd from the rest of the code in the main
method. Thus, the logic becomes clear and the program is easier to read.
2. The errors on computing the gcd are confined in the
gcd
method, which narrows the
scope of debugging.
3. The
gcd
method now can be reused by other programs.
Listing 5.7 applies the concept of code modularization to improve Listing 4.14, PrimeNum-
ber.java.
L
ISTING
5.7
PrimeNumberMethod.java
1
public class
PrimeNumberMethod {
2
public static void
main(String[] args) {
3 System.out.println(
"The first 50 prime numbers are \n"
);
4 printPrimeNumbers(
50
);
5 }
6
7
invoke
printPrimeNumbers
public static void
printPrimeNumbers(
int
numberOfPrimes) {
printPrimeNumbers
method
8
final int
NUMBER_OF_PRIMES_PER_LINE =
10
;
// Display 10 per line
9
int
count =
0
;
// Count the number of prime numbers
10
int
number =
2
;
// A number to be tested for primeness
11
12
// Repeatedly find prime numbers
13
while
(count < numberOfPrimes) {
14
// Print the prime number and increase the count
15
if
( ) {
16 count++;
// Increase the count
17
isPrime(number)
invoke
isPrime