top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

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

+1 vote
762 views

For Example:
the prime divisors of 450 are 4,5,3,3,2.

posted Jul 7, 2017 by Ajay Kumar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes
 
Best answer

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 by Salil Agrawal
0 votes

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 by Rohini Dv
Similar Questions
+6 votes

Given binary tree is:

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

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

+4 votes

I am trying to do something like this

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

and expecting

0x1010
+3 votes

Given a binary tree print it in inward spiral order i.e first print level 1, then level n, then level 2, then n-1 and so on.

For Ex -

         1 
   2           3 
 4    5       6     7 
8 9  10 11  12 13  14 15 

Print- 1 15 14 13 12 11 10 9 8 2 3 7 6 5 4

...