快速幂

以前头脑里面根本没有快速幂的概念,今天算接触了快速幂;
快速幂用来求m的n次方的,当 n很大时比如说n=1000000000,那么普通的O(n)求法会超时的(也不一定看出题人给的事件限制)。但有种做法是运用快速幂。可以把时间复杂度降到O(logn)。
比如,我想求2^21那么 我可以通过求2,2^4,2^16 求得。把21 分成1 4 16 。
原理:
以下以求a的b次方来介绍
把b转换成二进制数。
该二进制数第i位的权为
例如
11的二进制是1011
11 = 2?×1 + 2?×0 + 2?×1 + 2?×1
因此,我们将a??转化为算

下面以一个题目为例子

Key Set

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 388    Accepted Submission(s): 250


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   (1T105) , indicating the number of test cases. For each test case:

The first line contains an integer  n   (1n109) , 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-1)-1
可是n的最大值是1000000000 普通做法肯定会超时 故用快速幂求值

#include <iostream>

#include <cstring>
#include <cstdlib>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <iomanip>
#include <list>
#include <deque>
#include <stack>
#define ull unsigned long long
#define ll long long
#define mod 1000000007
#define INF 0x3f3f3f3f
#define maxn 10000+10
#define cle(a) memset(a,0,sizeof(a))
const ull inf = 1LL << 61;
const double eps=1e-5;
using namespace std;

bool cmp(int a,int b){
return a>b;
}
ll Pow1(ll a,ll n){
ll ans=1;
while(n){
if(n&1){
ans*=a;
ans%=mod;
}
a*=a;
a%=mod;
n>>=1;
}
return (ans+mod-1)%mod;
}
int main()
{
#ifndef ONLINE_JUDGE
//freopen("in.txt","r",stdin);
#endif
//freopen("out.txt","w",stdout);
int n,t;
cin>>t;
while(t--){
scanf("%d",&n);
printf("%I64d\n",Pow1(2,n-1));
}
return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值