Nica-Alejandria Canilang Nica-Alejandria Canilang - 4 months ago 18
Java Question

Getting factors using recursive method

The output was right but it keeps on displaying -1 at the end of the factors from time to time (infinite looping). I know there's something wrong with the while loop inside the recursion method but I don't know what it is. How can I stop the recursive call after getting the final answer? What should I use instead of while loop?

public static void main()
{
int num;
System.out.print("\fInput:");
num=kb.nextInt();
int temp=1;
factors(num, temp);

}



public static void factors(int num, int temp)
{

int count=2;


while (temp!=num)
{
if((num%count)==0)
{
System.out.print(count+ " * ");
factors(num/count, temp*count);
}
else
count++;
}
}

Answer

First, you don't need a recursion here. If you use recursion, you will always start new with count = 2, even if you already checked bigger values.

So, instead of

factors(num/count, temp*count);

I would just use

num = num/count;

Second, as Attila already said, you don't need the temp parameter and the real check you need is whether num != 1 is true.

If you really want to use recursion, there would be a better way: Pass the method factors the counter so that you don't always have to start with 2. In this case, you don't need any loop:

public static void main()
{
    int num;
    System.out.print("\fInput:");
    num=kb.nextInt();
    int count=2;
    factors(num, count);

}



public static void factors(int num, int count)
{  
    if (num == 1)
        return;

    if((num%count)==0)
    {
        System.out.print(count+ " * ");
        factors(num/count, count);
    }
    else 
        factors(num,count+1);
    }
}
Comments