Hello,
I am practicing iteration from a book and it has the following ex:
The greatest common factor (GCF) of two numbers is the largest number that evenly divides both numbers. Using Euclid�s method, create two codes for computing the GCF of two numbers. Use iteration for the first code and recursion for the other one.
Notes on Euclid�s algorithm:
1. Get input integers x and y.
2. Repeat the following step while y != 0
a. y = x % y;
b. x = old value of y
3. Return x.
For example, x = 14 and y = 6.
y = x % y = 14 % 6 = 2
x = 6
y = x % y = 6 % 2 = 0
x = 2 (GCF)
I tried this code with iteration and I am pasting it here:
public class ExerciseOne {
static int GCF(int x, int y){
while (y != 0){
y = x % y;
x = y;
}
return x;
}
public static void main(
String args[]){
System.out.println(GCF(14,6));
}
}
-----------------------------------------------------
Now I know the answer to this exercise is 2 and I am doing
something fundamentally wrong. Can anyone please point out what is the problem with my code?
I can see that x doesn't get the 'old value' of y. But I don't know how I can do it.
Shall be extremely grateful.
Thanks
Ricky