VB icon

Factorial of any length

Email
Submitted on: 1/3/2015 7:00:00 AM
By: Rishab Rana (from psc cd)  
Level: Beginner
User Rating: By 3 Users
Compatibility: C, C++ (general), Microsoft Visual C++
Views: 354
 
     Finds the factorial of large numbers.
 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
				
//**************************************
// Name: Factorial of any length
// Description:Finds the factorial of large numbers.
// By: Rishab Rana (from psc cd)
//
// Assumes:the program find out using simple multiplication the way we do on a paper.
1) find the length of the number so that we can have that big buffer
log10 of any number + 1 gives u the length of the number 
2) just multplies like we do on paper
//**************************************

#include <math.h>
#include <malloc.h>
#include <iostream.h>
#include <process.h>
void main()
{
	unsigned int d;	//number of digits
	unsigned char *a;
	unsigned int j, n, q, z, t;
	int i;
	double p;
	
	cout << "\nEnter the No\t:";
	cin >> n;
	p = 0.0; //calculate the number of digits required
	for(j = 2; j <= n; j++)
		p += log10(j);
	d = (int)p + 1;
	a = (unsigned char*)malloc(d*sizeof(unsigned char));
	if (!a)
	{
		cout << "Could not allocate memory!!!";
		exit(0);
	}
	for (i = 1; i < d; i++)
		a[i] = 0; //initialize
	a[0] = 1;
	p = 0.0;
	for (j = 2; j <= n; j++)
	{
		q = 0;	//initialize remainder to be 0
		p += log10(j);
		z = (int)p + 1;
		for (i = 0; i <= z/*NUMDIGITS*/; i++)
		{
			t = (a[i] * j) + q;
			q = (t / 10);
			a[i] = (char)(t % 10);
		}
	}
	cout << "\nThe Factorial is\n";
	// the fact is stored ulta..
	for( i = d -1; i >= 0; i--)
	{
		cout << (int)a[i];
	}
}


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Beginner category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.