Key Set
Problem Description
soda has a set S with n integers {1,2,…,n}. A set is called key set if the sum of integers in the set is an even number. He wants to know how many nonempty subsets of S are key set.
Input
There are multiple test cases. The first line of input contains an integer T (1≤T≤105), indicating the number of test cases. For each test case:
The first line contains an integer n (1≤n≤109), the number of integers in the set.
Output
For each test case, output the number of key sets modulo 1000000007.
Sample Input
4
1
2
3
4
Sample Output
0
1
3
7
分析:
一个排列组合问题。元素和为偶数,那么奇数肯定要调偶数个,偶数就无所谓了,所以偶数有2^(n/2)种选法,再乘以奇数有(C((n+1)/2,0)+C((n+1)/2,2).....)种选法,再减一,除去空集,注意,上面取奇数的时候用的是(n+1)/2(这里是向下取整的除法),是综合n为偶数和n为奇数两种情况。
组合数性质:C(n,1)+C(n,3)+....=C(n,2)+C(n,4)+....=1/2*(C(n,1)+C(n,2)+.....C(n.n))=1/2*(2^n)=2^(n-1)(n为奇数偶数都满足这个性质)
现在来把式子合并(这里的除法是真正的除法,所以n为奇数的时候要+1或-1再除):
1.n为偶数时,偶数有2^(n/2)种取法,奇数有2^(n/2)/2种取法,综合得ans=2^(n-1)-1
2.n为奇数时,偶数有2^((n-1)/2)种取法,奇数有2^((n+1)/2)种取法,综合得ans=2^(n-1)-1
剩下的就是快速幂取模了.
代码:
#include<cstdio>
#include<cmath>
#define m 1000000007
long long pow(int a,int b)
{
long long ans=1,base=a;
while(b>0)
{
if(b&1)
ans=(ans*base)%m;
base=(base*base)%m;
b>>=1;
//printf("ans=%d base=%d b=%d\n",ans,base,b);
}
return ans;
}
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
long long sum=pow(2,n-1)-1;
printf("%lld\n",sum);
}
return 0;
}