3的幂的模

3的幂的和 ##(51NOD-1013)


求:3^0 + 3^1 +…+ 3^(N) mod 1000000007


Input
输入一个数N(0 <= N <= 10^9)


Output
输出:计算结果


Sample Input
3


Sample Output
40


注释: (30+31+32+33+34) ( 3 0 + 3 1 + 3 2 + 3 3 + 3 4 ) % 1000000007 1000000007 =40 = 40


思路:先等比数列求和然后求模。


#include<stdio.h> 
#include<iostream>
#include<math.h> 
#include<cstdio>
typedef long long ll;
const ll mod=1000000007;
ll pow_mod(ll a,ll b,ll c)
{
    ll res=1;
    a%=c;
    while(b)
    {
        if(b&1) 
            res=res*a%c;
        a=a*a%c;
        b>>=1;
    }
    return res;
 }      //快速幂 

ll exgcd(ll a,ll b,ll &x,ll &y)
{
    if(b==0)
    {
        x=1;
        y=0;
        return a;
    }
    ll r=exgcd(b,a%b,x,y);
    int t=y;
    y=x-a/b*y;
    x=t;
    return r;       //回朔得到最大公约数 
}

ll inv(ll a,ll mod1)            //费马小定理求逆元 (任意数求逆元) 
{
    ll x,y;
    ll d=exgcd(a,mod1,x,y);
    if(d==1)    return (x%mod1+mod1)%mod1;  //如果x>mod则需要对mod求余,如果x<0,则要加上mod 
    return -1;
}

int main()
{                                                                                                                                                                                                                                                                  
    ll n,sum;
    while(~scanf("%lld",&n))
    {   sum=0;
        sum=(pow_mod(3,n+1,mod)-1)*inv(2,mod)%mod;
        printf("%lld\n",sum%mod);
    }
    return 0;
}


----------
或者是
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const ll mod=1000000007;
ll pow_mod(ll a,ll b,ll c)
{
    ll res=1;
    a%=c;
    while(b)
    {
        if(b&1)
            res=res*a%c;
        a=a*a%c;
        b>>=1; 
    }
    return res;
} 
ll inv(ll a,ll c)       //c必须是素数
{
    return pow_mod(a,c-2,c);
}
int main()
{
    ll n,ans;
    while(~scanf("%lld",&n))
    {
        ans=0;
        ans=(pow_mod(3,n+1,mod)-1)*inv(2,mod)%mod;
        printf("%lld\n",ans%mod);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值