Prime Factorization Program

I am writing a Prime Factorization function that outputs the factors of the number that is entered if it is prime. I have the function to test whether a number is prime or composite down, but I cannot correctly write the function to output the factors. For example, if the input is 24, the output should be 24 = 2*2*2*3. This is what I have so far.
1
2
3
4
5
6
7
8
9
10
11
12
13
  void PrimeFactorization (int x)
{
    int num;
    num = x;
    
    cout << x << " = ";
    
    for(int divisor = 2; num%divisor == 0; divisor++)
	{
		cout << divisor;
		num = num / divisor;
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
  for(divisor=2;num>1;)
  {
    for(;divisor<=num;divisor++)
    {
      if(num%divisor==0)
      {
        printf("%d\n",divisor);
        num/=divisor;
      	break;
      }
    }
  }
1) find a prime number (re-use last if it was successful from 3, else find next)
2) check if it is a factor of the number
3) If it is, divide it into number, and take the result, goto step 1, if new number is 1, quit you are done.

so 24..

find a prime, 2.
check it, yes, its a factor.
new number is 12
find a prime, 2 is still good as it worked last time
check it, its a factor
new number is 6
2 still good
yes
3 ------ you can avoid some work here if you test that the number being tested is prime. Or not. It works either way, testing for prime is more efficient.
2 still good
no
still 3
2 not good, next is 3
3 is
1, done!



Topic archived. No new replies allowed.