[51Nod](1013)3的幂的和 ---- 除法模运算

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

Input

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

Output

输出:计算结果

Input示例

3

Output示例

40

思路:
一开始wa了两次,发现不能很直白的就去取模,这样会有差错(因为不满足乘法模运算了)。
然后发现,可以把除法转换成乘法,即:(a/b)%mod = (a%(b*mod) / b) %mod。
这样就可以啦~ 不过这样子局限性比较大,1.要保证a被b整除,2.而且b*mod 不超int

当然最好的方法还是:逆元

感谢超霸的分析我推出的公式的问题~ORZ

AC代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod = 2*(1e9+7);
ll qpow(ll a,ll p)
{
    ll tmp = 1;
    while(p)
    {
        if(1&p) tmp = (tmp*a)%mod;
        a = (a*a)%mod;
        p>>=1;
    }
    return tmp;
}
int main()
{
    #ifdef LOCAL
    freopen("in.txt","r",stdin);
    #endif // LOCAL
    ios_base::sync_with_stdio(false);
    cin.tie(NULL),cout.tie(NULL);
    int n;
    cin>>n;
    ll ans;
    ans = qpow(3,n+1);
    cout<<((ans-1)%mod/2)%mod<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37624640/article/details/79931912