+ 1

factorial not working for big numbers like 100

#include<stdio.h> int factorial (int number); int main(){ printf("Please enter a number: "); int x ; scanf("%d",&x); printf("\nfactorial of %d is %d",x,factorial(x)); return 0; } int factorial(int number){ if (number == 1){ return 1; } else{ return number*factorial(number -1); } }

5th Nov 2019, 5:37 PM
Youssef Hall
Youssef Hall - avatar
8 odpowiedzi
+ 4
Here is your code with some changes. :) https://code.sololearn.com/cdj8VyHOWOhF/?ref=app You can also get the factorial of 1000. xD
5th Nov 2019, 6:05 PM
Chirag Kumar
Chirag Kumar - avatar
7th Nov 2019, 1:15 PM
Tanmay Gupta
Tanmay Gupta - avatar
+ 2
You are calculating factorial of 100 which is too large to be in the range of INT data type. And calculating factorial of big numbers makes your program looks slower and sometime you can't even get correct output!!
5th Nov 2019, 5:47 PM
Chirag Kumar
Chirag Kumar - avatar
+ 1
The reason is calculating the factorial takes a very long time for larger numbers. I would recommend you to look into a concept called Dynamic Programming to increase the processing speed. Although if you let your code run for a little while it should give the answer eventually
5th Nov 2019, 5:40 PM
Deep Lalwani
Deep Lalwani - avatar
0
How should I change it? I used long int but it isn’t working
5th Nov 2019, 5:51 PM
Youssef Hall
Youssef Hall - avatar
0
The only way to get over this problem is by optimising your code. The best way in this case is by using a concept called Dynamic Programming
5th Nov 2019, 5:54 PM
Deep Lalwani
Deep Lalwani - avatar
0
Youssef Hall you can achieve it by using "long double" Change you code, everywhere you type "int" change it to "long double" and also change the format specifier of int to long double i.e %Lf Then you can get factorial of 100.
5th Nov 2019, 6:02 PM
Chirag Kumar
Chirag Kumar - avatar
0
Thats great thanks. Its working online but not on my laptop. I’m using code blocks. Any reason why?
5th Nov 2019, 6:12 PM
Youssef Hall
Youssef Hall - avatar