【51Nod】1013 - 3的幂的和(等比数列 & 逆元)

来源:互联网 发布:python模拟鼠标点击 编辑:程序博客网 时间:2024/06/06 05:50

点击打开题目

1013 3的幂的和
基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题
 收藏
 关注
求:3^0 + 3^1 +...+ 3^(N) mod 1000000007
Input
输入一个数N(0 <= N <= 10^9)
Output
输出:计算结果
Input示例
3
Output示例
40



先用等比数列求和公式,ans = (3^(n+1) - 1)/ 2

然后用费马小定理对2求逆元,跑两次快速幂就行了。


代码如下:

#include <stdio.h>#include <cstring>#include <algorithm>using namespace std;#define CLR(a,b) memset(a,b,sizeof(a))#define INF 0x3f3f3f3f#define LL long longconst LL mod = 1000000007;LL quick_mod(LL a,LL n){LL ans = 1;while (n){if (n & 1)ans = ans * a % mod;a = a * a % mod;n >>= 1;}return ans;}int main(){LL n;scanf ("%lld",&n);LL ans = quick_mod(3,n+1);ans--;LL inv = quick_mod(2,mod-2);ans = ans * inv % mod;printf ("%lld\n",ans);return 0;}


0 0