Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Euclid's algorithm for greatest common divisor!!!

843789May 20 2009 — edited May 21 2009
Hi,

Can anyone tell me why is it giving me "*StackOverFlowError: null*" error in the 1st if statement. And how can I get rid of this.
Thanks

Euclid's algorithm for greatest common divisor*

This is a cunning algorithm for producing the greatest common divisor of two numbers by repeated subtraction:*

gcd (0,n) = 0*

gcd (m,n) = m, if m=n*

gcd (m,n) = gcd(n,m), if n<m //ensures m,n right way round*

gcd (m,n) = gcd(m,n-m)*


The last clause is the one that does most of the work: the repeated subtraction bit.*
import javax.swing.*;

public class GCommonDivisor{
  public static void main(String args[]){
      JOptionPane.showMessageDialog(null,"Give me two numbers to find the Greatest Common divisor of those two numbers.");
      String input = JOptionPane.showInputDialog("First Number : ");
      int Number1 = Integer.parseInt(input);
      String input2 = JOptionPane.showInputDialog("Second Number : ");
      int Number2 = Integer.parseInt(input2);
      System.out.println("The GCD is " +GCD(Number1, Number2));
    }
    
    public static int GCD(int N1, int N2){
        if(N1==0 && N2==N2){
            return N2;
        }
        else if(N1==N2){
            return N1;
        }
        else if(N1<N2){
            return GCD(N1, N2);
        }
        else{
            return GCD(N2,N1-N2);
        }
    }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 18 2009
Added on May 20 2009
13 comments
493 views