Matthew Johnson Matthew Johnson - 11 days ago 5
Java Question

For Loop to find the GCF of two int's

I am trying to write code that find the GCF of two numbers without using recursion (my teacher wants it using a for loop). My code right now doesn't seem to be working, I was wondering if anyone could spot the logic error.

public class Test
{
public static void main(String[] args)
{
System.out.print(findGCF(2, 12));
}
public static int findGCF(int a, int b)
{
int holderGCF = 0;
int greatestItCanBe = 0;
if(a > b)
{
greatestItCanBe = b;
}
else
{
greatestItCanBe = a;
}
for(int i = greatestItCanBe; i > 0; i--)
{
if((a % i == 0) && (b % i == 0))
{
holderGCF = i;
if(i > holderGCF)
{
holderGCF = i;
}
}
}
return holderGCF;
}
}

Answer

Here is the problem

holderGCF = i;
if (i > holderGCF) {
   holderGCF = i;
}

In above because of the first line after assignment holderGCF and i are having same values and your condition i > holderGCF is always false.

Remove this assignment.

holderGCF = i;
Comments