求:3^0 + 3^1 +...+ 3^(N) mod 1000000007
Input 输入一个数N(0 <= N <= 10^9) Output 输出:计算结果 Sample Input
3Sample Output
40
直接暴力是会超时的,得用到等比数列前n项和公式sum=a1(1-q^n)/(1-q).但数据很大,题目要求取余一个mod,那么就要把除以(1-q)改成乘以(1-q)对mod的逆元了(我们知道AB%C≠A%CB%C%C和(A∗B)%C=(A%C∗B%C)%C ,所以我们要将除法转为乘法,引入乘法逆元。)
暴力超时代吗:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define mod 1000000007
long long pow(long long x)
{
long long a=3,b=x,ans=1;
while(b)
{
if(b&1) ans=(ans*a)%mod;
a=(a*a)%mod;
b>>=1;
}
return ans;
}
int main()
{
long long n,s=0;
scanf("%lld",&n);
long long i;
for(i=0;i<=n;i++)
{
s=(s+pow(i))%mod;
}
printf("%lld\n",s);
}
引入乘法逆元:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define mod 1000000007
#define LL long long
LL pow(LL x)
{
LL a=3,b=x,ans=1;
while(b)
{
if(b&1) ans=(ans*a)%mod;
a=(a*a)%mod;
b>>=1;
}
return ans;
}
int main()
{
LL n;
scanf("%lld",&n);
printf("%lld\n",((pow(n+1)-1)*500000004)%mod);
}
拓展:求逆元
(4,7):7=4*1+3; 4=3*1+1;----->1=4-3=4-(7-4)=4*2-7;所以4对于7的逆元是2;
(5,14):14=5*2+4; 5=4*1+1;---->1=5-4=5-(14-5*2)=5*3-14; 所以5对于14的逆元是3;
(2,1000000007):1000000007=2*500000003+1; 2=1*1+1;1=2-1=2-(1000000007-2*500000003)=2*500000004-1000000007;所以2对于1000000007的逆元是500000004;