Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
December 3rd, 2012, 05:42 PM
 nishant_25
Registered User

Join Date: Dec 2012
Posts: 1
Time spent in forums: 18 m 34 sec
Reputation Power: 0
What is wrong in my code to calculate factorial of large numbers

Code:
`#include<stdio.h> int a[100],n1,temp=0,i=0,c=0,x; void factorial(int); void print(); int main() { a[0]=1; printf("enter number to calculate factorial\n"); scanf("%d",&n1); for(i=2;i<=n1;i++) { factorial(i); } print(); return 0; } void factorial(int n2) { temp=0; printf("%d\n",a[0]); for(i=0;i<=c;i++) { x=a[i]*n2+temp; a[i]=x%10; temp=x/10; } while(temp!=0) { c++; a[c]=temp%10; temp=temp/10; } } void print() { for(i=c;i>=0;i--) { printf("%d",a[i]); } }`

#2
December 4th, 2012, 01:05 AM
 salem
Contributed User

Join Date: Jun 2005
Posts: 4,247
Time spent in forums: 2 Months 4 Weeks 1 Day 11 h 34 m 37 sec
Reputation Power: 1809
What is wrong is that you didn't bother to check whether your post was readable before pressing "submit" and rushing off to wherever else you wanted to be.

FWIW, you can only get up to 12! on a 32-bit machine before you need to start doing something rather special. So my guess is that you're running into numeric overflow.
__________________
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper

#3
December 4th, 2012, 07:22 PM
 clifford
Contributing User

Join Date: Aug 2003
Location: UK
Posts: 4,959
Time spent in forums: 1 Month 4 Days 2 h 17 m 39 sec
Reputation Power: 1801
Include <stdint.h> and use uint64_t - that will be good for 20!

Beyond that you will either need to use a "bigint" library, or use floating point and accept a loss of precision (15 digits for double, 6 for float). A double has sufficient range for about 170!, but as I said only to 15 significant figures, the precise value is a 309 digit number - printing them all is probably mostly pointless even if you could calculate them.

 Viewing: Dev Shed Forums > Programming Languages > C Programming > What is wrong in my code to calculate factorial of large numbers