Search code examples
javastringprimes

Returning Prime Factorization in a particular form


My problem is that I need to take an inputted integer and return the prime factorization of it. It needs to be in the form of:

int * int * int * int

For example, the prime factorization of 180 would return:

2 * 2 * 3 * 3 * 5.

The code I have currently is:

public static String factor(int n)
{
    String str = "";
    if(isPrime(n)) {
        str = "" + n;
    }else if(n == 2) {
        str = "2";
    }else{
        for (int i = 2; i <= Math.sqrt(n); i++)
        {
            while (n % i == 0)
            {
                str = str + i;
            }
        }
    }
    return str;
}

The isPrime method mentioned is:

public static boolean isPrime(int n)
{
    if (n <= 1) {
        return false;
    }
    for (int i = 2; i <= n/2; i++)
    {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

Solution

  • In your while loop, you need to divide the remaining n value by each found factor. Otherwise, you'll never break out of the loop.

    while (n % i == 0) {
        str += (str.equals("") ? i : " * " + i);
        n /= i;
    }