您的位置:首页 > 其它

快速幂

2016-04-21 19:03 183 查看
以前头脑里面根本没有快速幂的概念,今天算接触了快速幂;快速幂用来求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的二进制是101111 = 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


[align=left]Problem Description[/align]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. 
[align=left]Input[/align]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. 
[align=left]Output[/align]For each test case, output the number of key sets modulo 1000000007. 
[align=left]Sample Input[/align]
4
1
2
3

[align=left]Sample Output[/align]
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: