题意:
给定n和m,求的结果是多少
题解:
化简过程。
最后化为等比数列求和公式,m^0 + m^1 + m^2 + ... + m^n = ? = (m^(n-1) - 1) / (m - 1)
代码:
#include <algorithm>
#include <iostream>
#include <numeric>
#include <cstring>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdio>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#define LL long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const double esp = 1e-6;
const double PI = 3.1415926535898;
const int INF = 0x3f3f3f3f;
using namespace std;
const long long MOD = 1e9+7;
long long pw[100010];
long long fast_pow(long long a,long long b){
long long res = 1;
while(b){
if(b & 1)
res = (res * a) % MOD;
a = (a * a) % MOD;
b >>= 1;
}
return res;
}
LL getans(LL m,LL n){
if(m==1)
return n+1;
LL a = fast_pow(m,n+1) - 1;
LL b = m - 1;
LL ans = (a * fast_pow(b,MOD - 2) % MOD) % MOD;
return ans;
}
int main(){
int T;
scanf("%d",&T);
while(T--){
LL n,m;
scanf("%lld%lld",&n,&m);
printf("%lld\n",getans(m,n));
}
return 0;
}
本文介绍了一种快速计算等比数列求和的方法,适用于大整数运算场景。通过化简公式并利用快速幂算法,实现了高效计算m^0+m^1+...+m^n的值,特别当m不等于1时。代码使用C++编写,并包含了一个快速幂函数以减少计算复杂度。
398

被折叠的 条评论
为什么被折叠?



