Prime factors using stack

Write a program that uses a stack to print the prime factors of a positive integer in descending order.

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
30
31
32
#include <iostream>
#include <stack>
using namespace std;


int main()
{
	int xnum, limit;
	stack<int> xPFac;
	{
		cout << "Please enter a positive integer: ";
		cin >> xnum;
		cout << endl;
		cout << "The prime factors of " << xnum << " in descending order are: ";
		
		limit = xnum / 2;

		for (int i = 2; i<= limit; i++)
		{
			if (xnum % i == 0)
				xPFac.push(i);
		}

		while (!xPFac.empty())
		{
			cout << xPFac.top() << " ";
			xPFac.pop();
		}
		cout << endl;
	}
	return 0;
}
I think my problem lies somehwere in :
1
2
if (xnum % i == 0)
xPFac.push(i);


Any suggestion.[
Last edited on
Can you use a sieve to generate the prime numbers then add to stack?
As far as your problem. You aren't checking if a number is prime before adding it to the stack what you are doing is checking if some number is evenly divisible by [2,num/2] and if so then add it to the stack. You may want to change your logic or read up on primes a little more. Basically a prime number is a number that is only divisible by 1 and itself. Examples: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29
Topic archived. No new replies allowed.