Fence Building(取模、逆元)

https://nanti.jisuanke.com/t/28963

题意:得出公式后,//(n-1)*(n-2)*(n^2-3*n+12)/24+n    //(n*(n-1)*(n-2)*(n-3)+(n-1)*(n-2)*12+24*n)/24  ,结果取模1e9+7,

 1<=n<=10^18.

题解:计算过程中每两个运算都要取模,对于除法,取逆元

逆元:因为涉及除数,不能直接像加减乘法一样分解取模,a*x=1+mod*y; 求出x,x就是a的逆元

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#define maxn 1005
#define mod 1000000007
#define LL long long
using namespace std;
LL n;
LL extgcd(LL a,LL b,LL &x,LL &y)//返回a和b的最大公约数 
{
	if(b==0)
	{
		x=1;y=0;
		return a;
	}
	LL q=extgcd(b,a%b,x,y);
	LL t=x;x=y;y=t-(a/b)*y;
	return q;
}
LL finv(LL a,LL m)//最小逆元 
{
	LL x,y;
	LL g=extgcd(a,m,x,y);
	x=(x%m+m)%m;
	return x;
}
int main()
{
	int t;
	cin>>t;
	int cnt=1;
	while(t--)
	{
		cin>>n;
		LL ans;
		ans=(((((((n%mod)*((n-1)%mod))%mod)*((n-2)%mod))%mod)*((n-3)%mod))%mod+((((((n-1)%mod)*((n-2)%mod))%mod)*12)%mod)%mod+(24*(n%mod))%mod)%mod;
		ans=(ans*finv(24,mod))%mod;
		cout << "Case #" << cnt++ << ": ";
		cout << ans << endl;
	}
	//(n-1)*(n-2)*(n^2-3*n+12)/24+n
	//(n*(n-1)*(n-2)*(n-3)+(n-1)*(n-2)*12+24*n)/24
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wwwlps/article/details/81280402
今日推荐