Search code examples
cfactorialdivide-by-zero

floating point exception for big output


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));
 }

Solution

  • 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;
    }