Simple Factorial program for larger numbers

It is a totally different approach, we are just playing with double.
As we know double has very large value 4.9e-324 to 1.8e+308.
Then we convert the double into an integer array.

Screenshot:
OUTPUT
The Code:


#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;

/*Classic factorial function to find the factorial of a number using recursion method*/
double factorial(int n)
{
 if(n==1)
 return 1;
 else
 return (factorial(n-1)*n);
}

int main()
{
 int n;
 cout<<"factorial of:  ";
 cin>>n;

 double r = factorial(n);
 double s = r;
 int i=0;
 /*to find the number of digits of the answer*/
 for(i=0; r>=1; i++)
 {
  r /= 10;
 }
 cout<<"number of digits:  "<<i<<endl;
 /*creating and dynamically allocated array*/
 int *a = new int[370];
 double t,u;
 int k;
 int l=0;
 /*type casting digit by digit of the answer and
  symultaneously storing into the array*/
 for(int j=i-1; j>0; j--)
 {
  t = s/pow(10,j);
  k = (double) t;
  a[l] = k;
  s = s-k*pow(10,j);
  l++;
 }
 /*Print the array*/
 cout<<"Answer:  ";
 for(int m=0; m<i; m++)
 {
  cout<<a[m];
 }
 cout<<endl;
 return 0;
}


This is an approximated program, boundary condition is 1-170.

Comments

Popular posts from this blog

Non Restoring Division Algorithm Implementation in C

Bit Stuffing Code Implementation in Java

Hackerrank Modified Kaprekar Numbers Solution