0

Please tell me why i am getting floating point exception in this code?It is working well for small numbers like n=1 or 2 but if i put n= 40 or a number bigger than that its giving me floating point exception.

 #include<stdio.h>
 int fact(unsigned long long int);
 int main()
 {
 int t;
 scanf("%d",&t);
 while(t--)
 {
 unsigned long long int n,k=0,i=0,sum=0;
 scanf("%llu",&n);
 for(i=1;i<=n;i++)
 {
 k=i;
 if(n==k)
 sum+=1;
 else
 sum+=fact(n)/(fact(k)*fact(n-k));
 }
 printf("%llu\n",sum%1000000007); 
 }
 return 0;
 }
 int fact(unsigned long long int n)
 {
 if(n==1)
 return 1;
 else
 return (n*fact(n-1));
 }
Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
shreyash
  • 7
  • 3
  • Floating-point exception? Really? There aren't any floating-point calculations in your program! – TonyK Aug 10 '14 at 14:22
  • 1
    @TonyK Floating-point exception means “integer division by zero”, and sometimes `INT_MIN / (-1)`. You have to go out of your way to cause a floating-point exception with floating-point computations (by default `1.0 / 0.0` evaluates to `+inf` without an exception, for instance). – Pascal Cuoq Aug 10 '14 at 15:52
  • @PascalCuoq: I don't understand your comment. If I try to perform an integer division by zero, I get an Integer Division by Zero exception (0xC0000094), not a floating-point exception. – TonyK Aug 10 '14 at 17:12
  • @TonyK Your system may flag a integer divide by 0 as a "Integer Division by Zero exception". Other systems will flag that as a "Floating-point Division by Zero exception" even with integer code. – chux - Reinstate Monica Aug 11 '14 at 18:21

1 Answers1

0

I see that your are calculating nC1 + nC2 + nC3 + ... nCn. For this you can use the following result :

nC0 + nC1 + nC2 + nC3 + ... nCn = 2 ^ n
nC1 + nC2 + nC3 + ... nCn = 2 ^ n - 1

Following is the code to do the same

#include<stdio.h>
#define MOD 1000000007
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        unsigned long long int n, i = 0, sum = 1;
        scanf("%llu", &n);
        for(i = 1; i <= n; i++)
        {
            sum = sum << 1;
            sum = sum % MOD;
        }
        sum = sum - 1;      
        printf("%llu\n", sum % MOD); 
    }
    return 0;
}
sujithvm
  • 2,351
  • 3
  • 15
  • 16