SPOJ: Bits. Exponents and Gcd (number of combinations + GCD)

Rastas's has been given a number n. Being weak at mathematics, she has to consider all the numbers from 1 to 2n - 1 so as to become perfect in calculations. (You can assume each number is consider as a soldier).

We define the strength of number i as the number of set bits (bits equal to 1) in binary representation of number i.

If the greatest common divisor of numbers a and b is gcd(a, b),

Rastas would like to calculate the function S which is equal to: 

As the friend of Rastas, it's your duty to calculate S modulo 109 + 7.

Input

The first line of the input contains the number of test cases, T. Each of the next T lines contains an integer n, as mentioned in the question

Output

For each value of n given, find the value of the function S.

Constraints

Sum of n over all test cases doesn't exceed 2500.

Example

Input:
5
Output: 
3
680

The meaning of the question: Given N, find ,

          That is, for these (i, j), i and j are expressed in binary, and the gcd of the number of 1s in the binary of i and j is accumulated.

Idea: Considering that 2^N-1 is very large, it is directly considered for binary, because there are at most 2500 1s, and O(N^2) can be done violently. We consider the number of combinations, enumerating (i,j) with X 1s and Y 1s, and the contribution is nun[X]*num[Y]*gcd(X,Y). When X equals Y, subtract yourself. Where num[X]=C(X,N);

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int Mod=1e9+7;
int c[2510],fac[2510];
int qpow(int a,int x){
    a%=Mod; int res=1;
    while(x){ if(x&1) res=(ll)res*a%Mod; a=(ll)a*a%Mod; x>>=1; } return res;
}
int gcd(int a,int b){
    if(b==0) return a;
    return gcd(b,a%b);
}
intmain ()
{
    int N,M,i,j,T,ans;
    fac[0]=1; for(i=1;i<=2500;i++) fac[i]=(ll)fac[i-1]*i%Mod;
    scanf("%d",&T);
    while(T--){
        ans=0; scanf("%d",&N);
        for(i=1;i<=N;i++){
            c [i] = (ll) fac [N] * qpow (fac [i], Mod- 2 )% Mod * qpow (fac [Ni], Mod- 2 )% Mod;
        }
        for(i=1;i<=N;i++) {
            for(j=1;j<=N;j++){
                if(i!=j) ans=(ans+(ll)c[i]*c[j]%Mod*gcd(i,j))%Mod;
                else ans=(ans+(ll)c[i]*(c[i]-1)%Mod*i)%Mod;
            }
        }
        ans = (ll) ans * qpow ( 2 , Mod- 2 )% Mod;
        printf("%d\n",ans);//
    }
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325114350&siteId=291194637
gcd
Recommended