记录一个菜逼的成长。。
找规律推导。
ans = (m^(n+1) - 1) / (m-1)
利用快速幂和乘法逆元对分数取模
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <list>
#include <deque>
#include <cctype>
#include <bitset>
using namespace std;
#define cl(a) memset(a,0,sizeof(a))
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const LL MOD = 1000000007;
LL PowerMod(LL a, LL b, LL c)
{
ULL ans = 1;
a = a % c;
while(b>0)
{
if(b % 2 == 1)
ans = (ans * a) % c;
b = b / 2;
a = (a * a) % c;
}
return ans;
}
LL gcd(LL a,LL b)
{
return b==0?a:gcd(b,a%b);
}
void exgcd(LL a,LL b,LL &x,LL &y)
{
if(b==0)
{
x=1;
y=0;
return ;
}
exgcd(b,a%b,x,y);
LL t=x;
x=y;
y=t-(a/b)*y;
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
LL n,m;
scanf("%lld%lld",&n,&m);
LL x, y;
LL tmp = PowerMod(m,n+1,MOD) - 1,mod = MOD;
m -= 1;
LL Gcd = __gcd(m,mod);
m /= Gcd;mod /= Gcd;
exgcd(m,mod,x,y);
LL ans = (x%mod+mod)%mod;
printf("%lld\n",tmp * ans % MOD);
}
return 0;
}
或者
#include<bits/stdc++.h>
#define mod 1000000007
using namespace std;
long long powt(long long a,long long b)
{
long long r = 1;
while(b)
{
if(b & 1) r = r * a % mod;
a = a * a % mod;
b >>= 1;
}
return r;
}
int main()
{
long long t,n,m;
scanf("%lld",&t);
while(t--)
{
scanf("%lld%lld",&n,&m);
printf("%lld\n",((powt(m,n + 1) - 1) * powt(m - 1,mod - 2) % mod + mod) % mod);
}
return 0;
}