Search code examples
javagreatest-common-divisor

getting wrong value with my gcd program


I just wrote a program to calculate the gcd of two numbers. I tested it with the numbers 6 and 4. My program returns a result of 4 which is obviously wrong because the gcd for 6 and 4 is 2.

import javax.swing.*;

public class Zahlen {
  public static long gcd(long m, long n){
    m = Long.parseLong(JOptionPane.showInputDialog("Enter value for m"));
    n = Long.parseLong(JOptionPane.showInputDialog("Enter value for n"));
    long tmp;
    while (n > 0) { 
      tmp = n;
      m = n;
      n = m;
      n = n%m;
    } // end of while
    return m;
  }

  public static void main(String[] args){
    System.out.print(Zahlen.gcd(6,4));
  }
}

Solution

  • Your algorithm code is incorrect. The fragment

    m = n;
    n = m;
    

    does nothing useful, and the value assigned to tmp isn't doing anything.

    Get the remainder, then assign the value of n to m, then the remainder to n. Use tmp for this purpose.

    while (n > 0) {
        tmp = m%n;
        m = n;
        n = tmp;
    }
    

    Additionally, why do you ask the user for m and n values in the method gcd if you already have parameters? Either don't ask in gcd and just use the parameters, or move the JOptionPane code to main, and pass the user's numbers into gcd there.