Reputation: 57
I don't think there is any point in my code I am reaching zero or dividing it with zero so can anyone help me why I am getting floating point exception for input 20 75
I am just calculating factorial for 2*n -1 and diving it with factorial of n and n-1 but I don't know where my code is getting zero or something else is reason
int fact(int num) {
if(num == 1 || num == 0) return 1;
else return (num*fact(num-1));
}
int Solution::solve(int A) {
int val1 = fact(A-1);
int val2 = fact(A-1+A-1);
int ans = (val2/((val1*val1)%1000000007))%1000000007;
return (ans/A)%1000000007;
}
for A = 20 or A = 75 I am getting floating point exception
Upvotes: 0
Views: 203
Reputation: 102
I can't add much but if you would change all int var = ...
variables to
long long int var = ...
(while I think that the long long int
is not recommended to use according to Google's Style Guide) it would work also with input of 20
becuase of the reasons mensioned in
previous comments:
long long int fact(long long int num) {
if(num == 1 || num == 0) return 1;
else return (num*fact(num-1));
}
int Solution::solve(int A) {
long long int val1 = fact(A-1);
long long int val2 = fact(A-1+A-1);
long long int ans = (val2/((val1*val1)%1000000007))%1000000007;
return (ans/A)%1000000007;
}
Upvotes: 0
Reputation: 238431
With input A = 20, you invoke fact(20 - 1)
and fact(20 - 1 + 20 - 1)
which are fact(19)
fact(38)
. Factorial of 19 is 121645100408832000 and factorial of 38 is 523022617466601111760007224100074291200000000.
On typical PC, the largest representable value for int
is 2147483647 which is less than either of the above factorials that you attempt to calculate. Your program overflows a signed integer, and behaviour of the program is undefined.
I don't think there is any point in my code I am ... dividing it with zero
(val1*val1)%1000000007
could be zero for some values of val1
. Therefore val2/((val1*val1)%1000000007)
may be dividing by zero. A simple case where that is the case is when val1
is zero and another case is where it is 1000000007. You may be thinking that val1
can never be either of those values since they are not factorials, but it can totally be either value when you have signed overflow in your program.
The largest factorial representable by as 32 bit integer is 12! and thus the largest input that your function can solve is A = 7.
Upvotes: 1