The following code segement is to calculate sum(K*((nCk)^2)) for 1<=k<=n and for n till 10^6, but the program starts giving absurb answer for n>20. Please help me. I think it may be because the product is not able to store such large value but what to do?
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int main()
{
int t;
scanf("%i",&t);
while(t--)
{
int n;
scanf("%i",&n);
double prod=1;
if (n!=1)
{
for(float i=1;i<n;i++)
{
prod = prod * (2+(i/(n-i))) ;
prod = fmod(prod,1000000007.0);
}
prod = prod * n;
}
else prod=1 ;
prod = int(prod)%1000000007;
cout<<prod;
printf("\n");
}
return 0;
}
You are doing
prod = prod * (2+(i/(n-i))) ;
You will lose precision when (i/(n-1)) is not integral and gives recurring decimal number. This will lead to unexpected results.