You are on page 1of 3

#include<iostream> #define BASE 10000 // Don't forget to change no.

of 0's displayable in Display() class Factorial // To save space 4 units per node { private: struct node { unsigned int data; node *link,*prev; node(int a = 0) { data = a; link = prev = NULL; } }; struct node *ans,*last; int fact; int no_of_nodes; public: Factorial(int a = 0) { no_of_nodes = 0; ans = last = NULL; fact = a; if( a == 0) { cout<<"Enter the number to find the factorial of "<<endl; cin>>fact; } else if(fact < 0) { cerr<<"No way to find factorial of negative numb ers.\nFactorial of -ve numbers isn't defined."<<endl; return; } } void Calculate() { if(ans != NULL) return; else { ans = last = NULL; } ans = new node(fact%BASE);no_of_nodes++; last = ans; int multiplier = fact/BASE; // Only one node cr eated this time while(multiplier > 0) { ans = new node(multiplier%BASE);no_of_nodes++; ans->link = last; last->prev = ans; multiplier /= BASE; last = ans;

} // Number saved last = ans; while(last->link != NULL) { last = last->link; } multiplier = fact - 1; while(multiplier > 1) { node *iter = last; int carry_out = 0 ; while(iter != NULL) { unsigned long int multiply = iter->data * multiplier + carry_out; iter->data = multiply%BASE; carry_out = multiply/BASE; iter = iter->prev; } while(carry_out > 0) { node *temp_node = ans; ans = new node(carry_out%BASE);no_of_nod es++; temp_node->prev = ans; ans->link = temp_node; carry_out = carry_out / BASE; } --multiplier; } } void Display()// Data will be deleted after display { node *iter = ans; while(iter != NULL) { if(iter->data < 10) // Single digit cout<<"000"<<iter->data; else if(iter->data < 100) // igit cout<<"00"<<iter->data; else if(iter->data < 1000) // digit cout<<"0"<<iter->data; else // Quadrupple digit cout<<iter->data; node *temp = iter; iter = iter->link; delete temp; } cout<<endl; } ~Factorial() { Tripple Double d

unsigned long int mem = no_of_nodes * sizeof(node); cout<<no_of_nodes<<" nodes created each of size "<<sizeo f(node)<<endl; cout<<"Memory usage = "; int i = 0; while(mem >1000 && i < 3) { mem /= 1000; ++i; } switch(i) { case 0: cout<<mem<<" bytes"<<endl; break; case 1: cout<<mem<<" Kb"<<endl; break; case 2: cout<<mem<<" Mb"<<endl; break; default: cout<<mem<<" Gb"<<endl; break; } cout<<"All of the memory was freed while displaying"<<en dl; } }; int main() { Factorial f; f.Calculate(); f.Display(); return 0; }

You might also like