Learn Computer Science programming - C# and C++ Algorithms

 
Factorial
The factorial of a positive integer n is the product of all positive integers less than or equal to n. Example: Factorial of 5 (5!) = 1 X 2 X 3 X 4 X 5 = 120. Below are two methods to accomplish this. The first is recursive and the latter is non-recursive. Which one is more performance?
Code
factorial.zip
File Size: 4230 kb
File Type: zip
Download File

#include <iostream>
#include <string.h>
#include <windows.h>
using namespace std;


struct StackNode //Stack
{
int d;
StackNode* Next;
};


class Stack
{
private:
StackNode* pHeader;
public:
Stack()
{
pHeader = NULL;
};
void Push(int d);
int Pop();
void Display();
};


void Stack::Push(int d)
{
StackNode* NewItem = new StackNode;
NewItem->Next = pHeader;
pHeader = NewItem;
NewItem->d = d;
}
int Stack::Pop()
{
if (!pHeader) cout <<endl << "Stack is empty" << endl;
else
{
int x = pHeader->d;
StackNode* DeletedItem = pHeader;
pHeader = pHeader->Next;
delete DeletedItem;
return x;
}
}


void Stack::Display()
{
cout << endl;
cout << endl << "Stack Content";


while (pHeader->Next)
{
cout << endl << pHeader->d;
pHeader = pHeader->Next;
}
cout << endl << pHeader->d;
}




int Factorial (int n )
{
cout << "n = " << n << endl;
    if (n == 0) 
return 1;
    else 
return n * Factorial(n-1);
}




double factorial (double n )
{
    if (n == 0) 
return 1;
    else 
return n * factorial(n-1);
}


double factorialNonRecursive (double n )
{
Stack stack;
double Result=1; 
double Num = n;
if (n == 0) 
return 1;
else
{
for (;n > 0; n--)
stack.Push (n);


double popped=stack.Pop ();


while (popped <= Num)
{
Result *= popped;
popped =  stack.Pop ();
}
}
return Result;
}


void main()
{


int x;
// -----------------------------------------------------------------------
wcout <<  endl << "*** Factorial ***" << endl;
wcout << "*************************************************" << endl;
double u = factorial(36);
cout << "Factorial of 36 is : " << u << endl;
// -----------------------------------------------------------------------
wcout <<  endl << "*** Factorial Non Recursive ***" << endl;
wcout << "*************************************************" << endl;
double ux = factorialNonRecursive(36);
cout << "Factorial of 36 is : " << ux << endl;


cin >> x;
 }