Search code examples
c++functionprime-factoring

Prime Factorization Function Output


I made this function that calculates the prime factorization of a number (n) which is obtained from the user. I am having issues with it due to the fact that It does not print the same factor more than once.

For Example:

The Prime Factorization of 3960 is:

11 5 3 3 2 2 2

However my program only prints out:

11 5 3 2

Can anyone help me to identify the cause and help me find a solution?

void primefact(int n)
{ 
    Stack f;
    assert(n >= 0);
    bool prime;

    for(int d = 2; d <= n; d++) // Test for factors > 1
    {
        if(n % d == 0)
        {
            prime = true;
            for(int j = 2; j < d; j++) // Test for prime
            {
                if(d % j == 0) // It is not prime
                prime = false;
            }
            if(prime)
                f.push(d);
        }
    }

    while(!f.empty())
    {
        cout << f.top() << endl;
        f.pop();
    }
}

Solution

  • Simplest code for prime factorization:-

    for ( int i = 2; i <= num; ++i )
    {
        while ( num % i == 0 ) 
        {
            num /= i;
            std::cout << i << std::endl;
        }
    }