*5.14 (Compute the greatest common divisor) Another solution for Listing 5.9 to find
the greatest common divisor of two integers n1 and n2 is as follows: First find d
to be the minimum of n1 and n2, then check whether d, d-1, d-2, . . . , 2, or 1 is
a divisor for both n1 and n2 in this order. The first such common divisor is the
greatest common divisor for n1 and n2. Write a program that prompts the user to
enter two positive integers and displays the gcd.
import java.util.Scanner; public class ProgrammingEx5_14 { public static void main(String[] args) { System.out.println("Enter two intergers:"); Scanner input = new Scanner(System.in); int n1 = input.nextInt(); int n2 = input.nextInt(); // find the minimum if (n2 < n1) { int temp = n2; n2 = n1; n1 = temp; } for (int d = n1; true; d--) { if (n1 % d == 0 && n2 % d == 0) { System.out.println("The GCD is:" + d); break; } } } }
No comments :
Post a Comment