Search code examples
javagreatest-common-divisor

Greatest Common Divisor Program Only Printing 1


I'm making a program where you put in two integers, and the program finds the greatest common divisor between the two numbers.

It runs fine, except it prints "1" as the GCD, even when the two numbers should have a different GCD. (Example: 4 & 64. GCD should be 4, but 1 still gets printed.) I can't figure out what's wrong with my code.

For those who want to answer using one method instead, I can't: It's an assignment that requires me to use two different methods in the same program. Please help?

Thanks for reading, and have a good week.

Here my code:

import java.util.Scanner;

public class greatestCommonDivisorMethod {

    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);

        //Number entry prompts       
        System.out.print("Please enter first integer: ");
        int num1 = input.nextInt();
        System.out.print("Please enter second integer: ");
        int num2 = input.nextInt();

        //Result printed
        System.out.println("The greatest common divisor of " +num1+ " and " +num2+ " is " +gcd(num1, num2)+".");
    }


    public static int gcd(int num1, int num2) {
        int gcd = 1;
        int k = 2;
        while (num1 <= k && k <= num2) 
        {
             if (num1 % k == 0 && num2 % k == 0)
                 gcd = k;
                 k++;  
        }

        return gcd;
    }
} 

Solution

  • while (num1 <= k && k <= num2) 
    {
          if (num1 % k == 0 && num2 % k == 0)
          gcd = k;
          k++;  
    }
    

    It looks like you accidentally switched num1 and k in your while loop.