Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

import java.util.*; import java.lang.Math; public class JavaApplication { privat

ID: 3742755 • Letter: I

Question

import java.util.*;
import java.lang.Math;

public class JavaApplication {
    private static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        int a;
        int b;
      
        System.out.println("Enter two numbers. This algorithm will find the greatest common denominator.");
        a = input.nextInt();
        b = input.nextInt();
        while (!(b == 0)) {
            if (a > b) {
                a = a - b;
            } else {
                b = b - a;
            }
        }
        System.out.println(a);
    }
}


JAVA coding! Could anyone explain to me step by step on how this Great Common Divisor code in Java works?

Explanation / Answer

import java.util.*;    // support Scanner class
import java.lang.Math;

public class JavaApplication {
    private static Scanner input = new Scanner(System.in); // Scanner class object input

    public static void main(String[] args) {
        int a;
        int b;
      
        System.out.println("Enter two numbers. This algorithm will find the greatest common denominator.");
        a = input.nextInt(); // use Scanner object input to input a
        b = input.nextInt(); // use Scanner object input to input b
        while (!(b == 0)) { // loop until one of the number becomes 0
            if (a > b) {
                a = a - b;
            } else {
                b = b - a;
            }
        }
        System.out.println(a);
    }
}

Inside while , the two numbers are compared and smaller number is subtracted from larger number until one of the number becomes 0

lets take numbers a = 15 and b = 20

as b> a

b = b-a = 20-15 = 5

Now a = 20 and b = 5

a> b , so a = a-b = 20-5 = 15

again a>b so a = a-b = 15-5 = 10

again a> b so a = a-b = 10-5 = 5

Now a = b , so b = b-a = 5-5 = 0

Loop exits and it prints the value of a which is 5

So 5 is the greatest common divisor of 15 and 20

Do ask if any doubt. Please upvote.