   # How to print all prime factor of a number in descending order using a stack?

+1 vote
124 views

For Example:
the prime divisors of 450 are 4,5,3,3,2. posted Jul 7, 2017

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;
}
`````` answer Jul 12, 2017

After finding prime members, store them in the stack.
smallest prime factor is found first and is at the bottom of the stack.
use another loop to pop elements from the stack, so the largest number at the top of the stack is displayed first hence in descending order. answer Jul 12, 2017
Similar Questions

Given binary tree is:

``````        1
/     \
2        3
/  \        \
4   5         6
/   \
7     8
``````

The output should be 1, 2, 3, 4, 5, 6, 7, 8

I am trying to do something like this

``````char a = 10;
printf("binary representation of a = %b",a);
``````

and expecting

``````0x1010
``````
``````         1