confusing prime factorization code, please help :(

Hi there! I was hoping for some help with this code for my school c++ class. We have to create a program that displays the prime factors of a number input by the user, even if some of the factors repeat. For example, the prime factors of an input 12 would be 2, 2, and 3. I already have most of it done, but I can't find where my error is. If I input 12, the factors display as 2 and 3, but if I input 15, then 2,3,4, and 5 are displayed. Please help me correct my code! Thank you so much for any help in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  #include <iostream>
using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main() 


{
	int value;
	int Answer;
	
	cout << "Input a value: ";
		cin >>value;
	
	
	for (int i=2; i<=value;i++)
		{
		 while (value % 2==0)
		 
		 	value /=i;
		 	Answer +=i;
		 	
		 	cout <<i<<" ";
		}
		
	
	return 0;
}
Last edited on
your code with proper indentation
1
2
3
4
5
6
7
for (int i = 2; i <= value; i++) {
  while (value % 2 == 0) //¿why 2?
    value /= i;
  Answer += i;

  cout << i << " "; //executes in every iteration of the for loop
}
you generally want this for a brute force approach.

for(i = 2; i < sqrt(n); i++)
{
if(n%i == 0)
if(isprime(i))
//its a prime factor. you need to write isprime.
//you also need to check n/i for the complimentary factor ( i*x = n)
}

another way to do it up to a point is multiply all the primes together and use gcd to pick off the PFs. At some point, like a factorial, this becomes too big to deal with.

Last edited on
Thank you both a bunches:) I was able to work it out!
Topic archived. No new replies allowed.