d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Java Program: Gcd Calculator
Add Reply New Topic New Poll
Member
Posts: 198
Joined: Mar 1 2005
Gold: 15.44
Oct 21 2012 04:56am
For my class I have to write a program that will solve for the GCD of two non-zero integers. I have to do so using the euclidean algorithm:

Number 1: x
Number 2: y

1. Subtract x from y until y < x
2. Swap the values of x and y.
3. Repeat the steps 1 and 2 until x = 0
4. y is the gcd.

Also, I must put the calculation for finding the divisor in a static method.

My teacher doesn't so much as teach us how to program as she does read from the book. So I'm having some difficulty self-learning.

What I have so far:

public static void main(String[] args)
{

Scanner sc = new Scanner(System.in);
System.out.println("Greatest Common Divisor Finder");
String answer = "y";

while (answer.equalsIgnoreCase("y"))
{
System.out.print("Enter First number: ");
int firstNumber = sc.nextInt();
System.out.print("Enter Second number: ");
int secondNumber = sc.nextInt();
}
}

Now I'm working on the next method to find the divisor, and I know logically what I want to do, but I'm just not sure how to do it.
The way I see it, I need subtract x from y until it's zero, seems simple enough but I'm not sure where to go. Is there a difference between using an if or a while statement here?

If I had to take a guess, I would try a while loop,
while ( (x-y) != 0)
{
int difference = x - y
}

What I don't know is how i'll flip flop the x and y once y is less than x.

Any help would be greatly appreciated!
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Oct 21 2012 05:33am
Code
public int GCD(int a, int b)
{
  if (b==0) return a;
     return GCD(b,a%b);
}


hows that?
Member
Posts: 165
Joined: May 23 2012
Gold: 474.50
Oct 21 2012 12:44pm
Yours would work carteblanche, but doesn't use the euclidean algorithm.

This should work:

Code
public int GCD(int a, int b) {

 if(x == 0) return y;
 
 if(x < y) {
   return GCD(x, y-x);
 } else {
   return GCD(y, x-y);
 }
}


This post was edited by Kimano on Oct 21 2012 12:49pm
Member
Posts: 198
Joined: Mar 1 2005
Gold: 15.44
Oct 21 2012 02:23pm
cartblance, your solution is the one I was able to find online and seems the best, but my teacher wanted the euclidean method for whatever reason.

Kimano, thanks so much! I was just having difficulty seeing how it would loop, but I think I get it now.
Member
Posts: 11,637
Joined: Feb 2 2004
Gold: 434.84
Oct 22 2012 04:34pm
Quote (Dairyfreeze @ Oct 21 2012 03:23pm)
cartblance, your solution is the one I was able to find online and seems the best, but my teacher wanted the euclidean method for whatever reason.

Kimano, thanks so much! I was just having difficulty seeing how it would loop, but I think I get it now.


The technique they showed is called recursion and it's handy.
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll