Search code examples
javagreatest-common-divisor

Fix GCD of two integers


I am a beginner in Java. I was asked to write a program that finds the GCD of two numbers entered by the user. I tried this but no output, how to fix it?

import java.util.Scanner;

public class myclass {

    public static void main(String args[]) {

        Scanner scan = new Scanner(System.in);

        int a = scan.nextInt();
        int b = scan.nextInt();

        if (a < b) {
            for (int c = a; c < 0; c--) {
                if (a % c == 0 && b % c == 0) {
                    System.out.print(c);
                }
            }

            if (b < a) {
                for (int c = b; c < 0; c--) {
                    if (b % c == 0 && a % c == 0) {
                        System.out.print(c);
                    }
                }
            }
        }
    }
}

Solution

  • Others have fixed your code already. If you would like a shorter approach you can look at this example:

    public static void main(String[] args) {
        int a = 60;
        int b = 24;
    
        for(int i = Math.min(a, b); i > 0; i--){
            if(a % i == 0 && b % i == 0){
                System.out.println("GCD: " + i);
                break;
            }
        }
    }
    

    Output:

    GCD: 12

    By using Math.min() you don't have to create two loops to see whether a is where you should start, or b.