Hi everyone, I've been taking a class on cprogramming and have been successful up thus far. I am now learning about stacks and am having tremendous problems. I've written a program that will calculate the prime factors of numbers. The only problem is that I needed to reverse the output as show in the example below
e.g. Prime factors of #
1
2
3
4

need printout to read
4
3
2
1

I understand the concept in which the output will first be stored in an array [1,2,3,4] but am not entirely sure on how to retreive it without making the program really long. I know about pop functions but have only used this with push empty and full functions in class. I am just having problems on trying to figure out how to implement it here.
I've tested my prime factorization program by itself and I know it works but when I try to integrate it into the stack I get numerous errors and I am not sure if I am on the right track
Please let me know if you have any suggestions. I feel as if I am close but am started to get frustrated because it feels as if I am missing something small
Any help will be greatly appreciated

Thanks in advance
Sean

#include <iostream.h>
const int STACK_MAX= 20;
typedef int StackElement;

class Stack
 {
  private:
   StackElement StackArray[STACK_MAX];
   int StackTop;

 public:
  bool empty();
  int primefactor(int number);
  bool full( );
    bool isprime(int number);
    void push(const StackElement & value);
    void pop();
  int top();
  void display();

    Stack::Stack()                          //Constructor
   {
    StackTop=-1;

   }

  Stack::primefactor(int number)
{
   bool isPrime = isprime();
   int prime = number;
   int i = 2, j;
   double squareroot = sqrt(static_cast<double>(number));
  int count = 0;
   cout << "The prime factorization of the number " << number << " is:" << endl;
  if(isPrime)
      cout << space << number << " is a prime number." << endl;
   else {
      while((prime > 0) && (i <= number)) {
         if((prime % i) == 0) {
        count++;
        for(j = 0; j < count; j++)
          cout << space;
            cout << i << " is a factor" << endl;
            prime /= i;
      } else         
           i++;
      }
 return true;
}


   void Stack::push(const StackElement & value)   //Add value to the Stack
   {
    if(StackTop<STACK_MAX-1)                     //If Stack is not full add element
      {
       ++StackTop;
       StackArray[StackTop]=value;
      }
    else
     cout<<"Stack is full. \n";
   }



  inline bool Stack::empty() const       //Check for emptyness
   {
    return(StackTop==-1);
   }

}

   
    bool isprime(int number)
{
   int i;
   
   for(i = 2; i < number; i++) {
      if((number % i) == 0)
         return false;
   }
   


    StackElement Stack::top()const     //function to retireve value at top of Stack
     {
      if(StackTop>=0)                   //If Stack is not empty perform task
       return StackArray[StackTop];
      else
      cout<<"Stack is empty\n";
      }

     void Stack::pop()         //Function to discard value at top of Stack
      {
       if(StackTop>=0)        //If Stack is not empty perform task
        StackTop--;
       else
       cout<<"Stack is empty\n";
      }

   void Stack::display()     //Function to write the entire stack
    {
     for(int i=StackTop;i>=0;i--)
     cout<<StackArray[i]<<endl;
    }
               
int main()
 {
    Stack factors;
  int number;
   
  cout << "Enter a number > 1000 ";
   cin >> number;

  
   
      factors.primefactor();
      factors.top();
      factors.pop();
      factors.display();
    };

Dani AI

Generated

Short answer: collect the factors into the stack while factoring, then pop and print after factoring completes. The common mistakes in the thread are (a) printing inside primefactor instead of pushing the factor, (b) wrong Push/Pop signatures and calls (e.g. Pop should not take a parameter), and (c) calling methods on the class name instead of the instance. As suggested, push each factor when it is found and then pop/print in main.

Concrete fixes and signatures to use:

  • void Push(int value); — store at array[top++] after checking capacity.
  • int Pop(); — check empty, then return array[--top].
  • bool IsEmpty() const; — return top == 0.
  • Inside primefactor, replace the cout << i ... lines with a call to Push(i) so the factors are saved rather than printed.
  • In main call the instance method and then pop/print, for example:
    mystack.primefactor(number);
    while (!mystack.IsEmpty())
      cout << mystack.Pop() << " is a factor" << endl;

A few correctness notes and tips:

  • Use prime > 1 as the loop condition (stop when the remaining value is 1). The simple factor loop is: test small divisors and divide repeatedly; if a leftover > 1 remains it is a prime factor and should be pushed as well. That avoids repeatedly calling is_prime inside the inner loop.
  • Do not use Pop() as a sentinel-returning function (returning 0 to mean empty). Instead, check IsEmpty() before popping; returning 0 can hide bugs.
  • Initialize top consistently (0 for empty) and guard against overflow/underflow when pushing/popping.
  • For less bookkeeping, modern code can use std::vector<int> or std::stack<int> to collect factors and then iterate or pop to print in reverse.

These steps address the compile/logic problems seen in 's posts while keeping the stack behavior explicit and robust.

Recommended Answers

All 5 Replies

This is a copy of my prime number code before implementing the stack

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

const string SPACE_STR = "   ";

void prime_factor(int number);
bool is_prime(int number);

int main() {
   int number;

   cout << "Enter a number > 1000 -> ";
   cin >> number;

   prime_factor(number);

   return 0;
}

// Function I need help with.

void prime_factor(int number)
{
   bool isPrime = is_prime(number);
   int prime = number;
   int i = 2, j;
   double squareRoot = sqrt(static_cast<double>(number));
	int count = 0;
   
   cout << "The prime factorization of the number " << number << " is:" << endl;
	
	if(isPrime)
      cout << SPACE_STR << number << " is a prime number." << endl;
   else {
      while((prime > 0) && (i <= number)) {
         if((prime % i) == 0) {
				count++;
				for(j = 0; j < count; j++)
					cout << SPACE_STR;
            cout << i << " is a factor" << endl;
            prime /= i;
			} else         
         	i++;
      }
   }
}

bool is_prime(int number)
{
   int i;
   
   for(i = 2; i < number; i++) {
      if((number % i) == 0)
         return false;
   }
   
   return true;
}

Why not just run the original program's loop down from sqrt(number) down to 2, rather than go up? Yes, you'd have to check i with is_prime(), but the numbers would come out in the right order.

If you really want to use a stack, there are standard stack classes, but you could do it without a class very simply too. If it were me, I'd probably do a simple simple simple class:

static const int MAX_STACK = 1000;
class AnIntStack
{
public:
    AnIntStack()    { m_top = 0; }
    void Push(int n) { if (m_top < MAX_STACK) m_stack[m_top++] = n; }
    int Pop(int n) { if (m_top > 0) return m_stack[--m_top]; else return 0; }
    bool IsEmpty() const { return (m_top <= 0); }
protected:
int m_stack[MAX_STACK];
int m_top;
};

and then in your *original* code where you did the output you would say something like mystack.Push(i); and in the main you would have a final loop saying something like "while (!mystack.IsEmpty()) <print element mystack.Pop()>

Is that what you were after?

Hello thanks for the tips. I've rewritten most of my code and came up with what's below. I am receiving 3 errors so I am unable to troubleshoot or see if there will be errors in the output. I believe that it is definitely close now. I know that the errors are with my function calls at the end but I thought that this was the method used for calling them.

Example: in the code (w/o stack) if I enter 36 It should return the prime factors
2 is a factor
2 ""
3 ""
3 ""

With the stack implemented now it is supposed to now return
3 is a factor
3 ""
2 ""
2 ""

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

const string SPACE_STR = "   ";

static const int MAX_CAPACITY = 1000;
class Stack
{
public:
    Stack()    { top = 0; }
    void primefactor (int number);
	bool is_prime(int number);
	void Push(int number) ;
    int Pop(int number) ;
  
	
private:
int arraystack[MAX_CAPACITY];
int top;
};

// Function I need help with.

void Stack::primefactor(int number)
{
   bool isPrime = is_prime(number);
   int prime = number;
   int i = 2, j;
   double squareRoot = sqrt(static_cast<double>(number));
	int count = 0;
   
   cout << "The prime factorization of the number " << number << " is:" << endl;
	
	if(isPrime)
      cout << SPACE_STR << number << " is a prime number." << endl;
   else {
      while((prime > 0) && (i <= number)) {
         if((prime % i) == 0) {
				count++;
				for(j = 0; j < count; j++)
					cout << SPACE_STR;
            cout << i << " is a factor" << endl;
            prime /= i;
			} else         
         	i++;
      }
   }
}

bool Stack::is_prime (int number)
{
   int i;
   
   for(i = 2; i < number; i++) {
      if((number % i) == 0)
         return false;
   }
   
   return true;
}


void Stack::Push(int number)
{ if (top < MAX_CAPACITY) 
	arraystack[top++] = number; 

}
int Stack::Pop(int number) 
 { if (top > 0) return arraystack[--top]; else return 0; 
 }


int main() {
   int number;

   cout << "Enter a number > 1000 -> ";
   cin >> number;

   Stack::primefactor();
   Stack::Push();
   Stack::Pop();
   return 0;
}

Hi, I have completed the code so and am now able to compile but for some reason it will not take the output and reverse it

example prime factors of 100
2
2
5
5

I am still trying to get it to print
5
5
2
2

It seems as if everything is written correctly but the output has not changed :sad:

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

const string SPACE_STR = "   ";

static const int MAX_CAPACITY = 1000;
class Stack
{
public:
    Stack()    { top = 0; }
    void primefactor (int number);
	bool is_prime(int number);
	void Push(int number) ;
    int Pop(int number) ;
  
	
private:
int arraystack[MAX_CAPACITY];
int top;
};

// Function I need help with.

void Stack::primefactor(int number)
{
   bool isPrime = is_prime(number);
   int prime = number;
   int i = 2, j;
   double squareRoot = sqrt(static_cast<double>(number));
	int count = 0;
   
   cout << "The prime factorization of the number " << number << " is:" << endl;
	
	if(isPrime)
      cout << SPACE_STR << number << " is a prime number." << endl;
   else {
      while((prime > 0) && (i <= number)) {
         if((prime % i) == 0) {
				count++;
				for(j = 0; j < count; j++)
					cout << SPACE_STR;
            cout << i << " is a factor" << endl;
            prime /= i;
			} else         
         	i++;
      }
   }
}

bool Stack::is_prime (int number)
{
   int i;
   
   for(i = 2; i < number; i++) {
      if((number % i) == 0)
         return false;
   }
   
   return true;
}


void Stack::Push(int number)
{ if (top < MAX_CAPACITY) 
	arraystack[top++] = number; 

}
int Stack::Pop(int number) 
 { if (top > 0) return arraystack[--top]; else return 0; 
 }


int main() {
   Stack mystack;
	int number;

   cout << "Enter a number > 1000 -> ";
   cin >> number;

	mystack.primefactor(number);
	mystack.Push(number);
	mystack.Pop(number);
   

   return 0;
}

In your code, where you have:

cout << i << " is a factor" << endl;

That's where you should INSTEAD say:

mystack.Push(i);

So, now it puts things onto the stack instead of printing them. In your main routine, where you now do Push and Pop, you instead need a loop that pops off each pushed number and prints that number out. something like:

int i;
while (i = mystack.Pop())
    cout << i << " is a factor" << endl;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.