twc
Posts: 129
Nickname: twc
Registered: Feb, 2004
|
|
Re: Greatest Common Divisor Program Help
|
Posted: May 4, 2004 1:57 PM
|
|
> System.out.println("The greatest common divisor of:\t" + x + "\tand\t" + y + "\tis\t" + y);
Look at your code. You are printing x once and y twice. If the algorithm is working, one of those should be equal to the divisor, and the other should be zero. Actually, I would have thought that your output would be zero, and the divisor twice.
Your problem is caused by the fact that the values of x and y are being changed while the program figures out what the common divisor is. By the time that you print out the results, the original values are long gone.
There are two ways to fix this. One way is to create two more int variables to store the original values. That way after x and y have been modified by your algorithm, you would still have the original x and y values.
A better way would be to move the code that finds the common divisor into a method and use x and y as parameters. That way they never get modified in the first place. The method would work only on copies of x and y. I would also make the parameter names different for clarity. Here is an idea of what I mean.
int comDiv = getCommonDivisor(x, y);
System.out.println("The greatest common divisor of:\t" + x + "\tand\t" + y + "\tis\t" + comDiv);
//elsewhere in your program - NOT in the main method
public static int getCommonDivisor(int a, int b){
// put all of your code that finds the divisor here (don't forget to change variable names to a and b!!!!)
}
I hope this helps.
|
|