首先了解一下快速幂运算,本来我是想自己敲完这篇博客关于快速幂运算部分的,但是数学公式不太好敲,这里给出一篇博客链接 对对对,链接就是我,具体也可以参考书 挑战程序设计竞赛123页的讲解,为了加深理解,手动敲一下快速幂运算的代码
1.
typedef long long ll;
ll mod_pow(ll x,ll n,ll mod)
{
ll sum = 1;
while(n)
{
if(n&1)
sum = sum * x % mod;
x = x * x % mod;
n >>= 1;
}
return sum;
}
本题代码
#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <queue>
#include <stack>
#include <cstring>
#include <map>
#include <list>
using namespace std;
//const int maxn = 0x3f3f3f3f;
const int mod = 1000000007;
typedef long long ll;
ll mod_pow(ll x,ll n,ll mod)
{
ll sum = 1;
while(n)
{
if(n&1)
sum = sum * x % mod;
x = x * x % mod;
n >>= 1;
}
return sum;
}
int main()
{
int t,ca = 1;
cin>>t;
while(ca<=t)
{
int n;
cin>>n;
printf("Case #%d: %lld\n",ca++,mod_pow(2,n-1,mod)*n%mod);
}
return 0;
}
2.
typedef long long ll;
ll mod_pow(ll x,ll n,ll mod)
{
if(!n)
return 1;
ll sum = mod_pow(x*x,n/2,mod);
if(n&1)
sum = sum * x % mod;
return sum;
}
本题代码
#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <queue>
#include <stack>
#include <cstring>
#include <map>
#include <list>
using namespace std;
//const int maxn = 0x3f3f3f3f;
const int mod = 1000000007;
typedef long long ll;
ll mod_pow(ll x,ll n,ll mod)
{
if(!n)
return 1;
ll sum = mod_pow(x*x,n/2,mod);
if(n&1)
sum = sum * x % mod;
return sum;
}
int main()
{
int t,ca = 1;
cin>>t;
while(ca<=t)
{
int n;
cin>>n;
printf("Case #%d: %lld\n",ca++,mod_pow(2,n-1,mod)*n%mod);
}
return 0;
}