Trouble with factor generator

723 views Asked by At

I'm having some trouble in completing this factor generator from my programming class. It's supposed to take a number, and print out all the factors using the nextFactor method. When I set the number to factor to let's say 150, it prints out "1 2 3 5", where it's supposed to print "2 3 5 5". So, where should I go from here? I've looked at Java - Factor Generator program nextfactor method, but it didn't awnser any of my inqueries

public class FactorGenerator
{
    //user inputs int from scanner in FactorTester class
    public FactorGenerator(int i)
    {
        num = i;
    }

    //Checks to see if num can be factored, but does not factor it.
    //Goes through all possible factors of num and returns true if the remainder == 0
    public boolean hasMoreFactors()
    {       
        for(int i = 1; i < num; i++)
        {
            //check if the remainder is anything other then 0
            if(num % i == 0)
            {
                return true;
            }
        }

        return false;
    }

  //Actually factors num and prints out the factor at the end of every loop.
    public void nextFactor() 
    {
        for(int i = 1; i < num; i++)
        {
            //check if the remainder is anything other then 0
            if(num % i == 0)
            {
                System.out.println(i);
                num /= i;
            }            


        }

        System.out.println("Done.");
    }

    private int num;
}
2

There are 2 answers

1
BevynQ On BEST ANSWER

try this factors can duplicate so you need to loop until you have extracted all the instances of that factor

public void nextFactor() 
{
    for(int i = 2; i <= num; i++)
    {
        //check if the remainder is anything other then 0
        while (num >= i && num % i == 0)
        {
            System.out.println(i);
            num /= i;
        }           

    }

    System.out.println("Done.");
}

an alternative way is to do the increment in the body of the loop

public void nextFactor() 
{
    for(int i = 2; i <= num;)
    {
        //check if the remainder is anything other then 0
        if (num % i == 0)
        {
            System.out.println(i);
            num /= i;
        } else {
           i++;
        }

    }

    System.out.println("Done.");
}
1
Taylor On

For starters, it will always print out 1 because any integer / 1 will always have remainder of zero. You can start i from 2 instead of 1 in your for if you want to skip 1.

I'd suggest something like this: (note this is based in part on BevynQ's answer below):

for(int i = 2; i <= num; i++){
    while (num >= i && num % i == 0) {
        System.out.println(i);
        num /= i;
    }
}