51nod 1013 3的幂的和(费马小定理+快速幂 or 矩阵快速幂)

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



解法一:直接利用等比数列求和公式,得到 [ (pow(3,n+1) - 1 ) / 2 ] % m。又因为m=1e9+7,是质数。然后就可以利用费马小定理+快速幂就可以求解 逆元。推导过程见 51nod 1119


代码如下:


#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int mod = 1e9+7;

LL pow_quick(LL n,LL m)
{
	LL res=1;
	while(m)
	{
		if(m&1)
			res = (res*n)%mod;
		n = (n*n)%mod;
		m>>=1;
	}
	return res;
}

void slove(LL n)
{
	//n++;
	LL ans=pow_quick(3,n+1)-1;
	ans = (ans*pow_quick(2,mod-2)) % mod;
	printf("%lld\n",ans);
}

int main()
{
	LL n;
	while(scanf("%lld",&n)!=EOF)
		slove(n);
	return 0;
} 



解法二:直接利用矩阵快速幂,可以避免逆元运算。  


矩阵如下:            sn                sn-1            3    1

                                         =                  *      

                               1                     1             0     1


代码如下:


#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef vector<LL> vec;
typedef vector<vec>	mat;
const int mod = 1e9+7;

mat mul(mat &A,mat &B)
{
	mat C(A.size(), vec(B[0].size()));
	for(int i=0;i<A.size();++i)
	{
		for(int k=0;k<B.size();++k)
		{
			for(int j=0;j<B[0].size();++j)
				C[i][j] = (C[i][j]+A[i][k]*B[k][j]) % mod;
		}
	}
	return C;
}

mat pow_quick(mat A,LL n)
{
	mat B(A.size(), vec(A.size()));
	for(int i=0;i<A.size();++i)
		B[i][i]=1;
	while(n>0)
	{
		if(n&1)
			B=mul(B,A);
		A=mul(A,A);
		n>>=1;
	}
	return B;
}


int main()
{
	LL n;
	while(scanf("%lld",&n)!=EOF){
		mat A(2, vec(2));
		A[0][0]=3;	A[0][1]=1;
		A[1][0]=0;	A[1][1]=1;
		A = pow_quick(A,n+1);
		printf("%lld\n",A[0][1]);
	}
	return 0;
} 



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值