Skip to content

Instantly share code, notes, and snippets.

@Shravan40
Created September 8, 2013 09:01
Show Gist options
  • Save Shravan40/6483111 to your computer and use it in GitHub Desktop.
Save Shravan40/6483111 to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
int nChoosek( unsigned n, unsigned k )
{
if (k > n)
return 0;
if (k * 2 > n)
k = n-k;
if (k == 0)
return 1;
int result = n, temp;
for( int i = 2; i <= k; ++i ) {
result *= (n-i+1);
result /= i;
}
return result;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n ,k;
cin>>n >>k;
int arr [k];
int r = n/k;
int rem = n%k;
for(int i = 0; i< k; i++)
{
arr[i] = r;
}
for(int i = 1; i <= rem; i++)
{
arr[i]++;
}
int res = 0;
res += nChoosek(arr[0],2);
if(k%2 == 0)
{
int i;
for(i =1; i<(k+1)/2; i++)
{
res += ( nChoosek(arr[i],1) * nChoosek(arr[k-i],1) );
}
res += nChoosek(arr[i],2);
}
else
{
for(int i=1; i< (k+1)/2; i++)
{
res += ( nChoosek(arr[i],1) * nChoosek(arr[k-i],1) );
}
}
cout<<res<<"\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment