Just iterate in the increasing order from 2 to n-1 assuming n is the number to be checked and in each iteration check
- if iteration is the factor of the n and is prime
- if above condition is met then push the number in the stack else continue
- After the loop is over just pop everything from the stack and present.
PS: Your example is wrong 450 has prime factor as 5, 3, 2 and 1. 4 is not a prime number.
Following is the code (tested one)
#include <iostream>
#include <stack>
using namespace std;
bool isprime(int number)
{
int i;
for (i=2; i<number; i++)
if (number % i == 0)
return false;
return true;
}
int main()
{
int number=450, halfNumber;
stack<int> smallPrimeFac;
smallPrimeFac.push(1);
if((number % 2) == 0)
smallPrimeFac.push(2);
for (int i = 3; i < number; i++)
{
if ((number % i == 0) && (isprime(i)))
{
smallPrimeFac.push(i);
}
}
cout << "\nThe prime factors of " << number << " are: ";
while (!smallPrimeFac.empty())
{
cout << smallPrimeFac.top() << " ";
smallPrimeFac.pop();
}
return 0;
}