同余定理,逆元,费马小定理求逆元

                                                                    逆元 Inverse element

1.什么是逆元

当求解公式:(a/b)%m 时,因b可能会过大,会出现爆精度的情况,所以需变除法为乘法:

设c是b的逆元,则有b*c≡1(mod m);//(b*c-1)%9973=0 ,我们称 c 是 b 关于 m 的乘法逆元

则(a/b)%m = (a/b)*1%m = (a/b)*b*c%m = a*c(mod m);

即a/b的模等于a*(b的逆元)的模;

一般用inv(b)来表示b的逆元

若对于数字A,C 存在X,使A * X = 1 (mod C) ,那么称X为 A 对C的乘法逆元。

2.求逆元的方法

(1).费马小定理,下面的例题1就是使用的费马小定理

费马小定理的应用条件:mod必须是素数,并且gcd(b,mod)=1,

inv(b)=b^(mod-2)  这就需要用到快速幂了

逆元就是这样应用的;

***************************************************

例题1

要求(A/B)%9973,但由于A很大,我们只给出n(n=A%9973)(我们给定的A必能被B整除,且gcd(B,9973) = 1)。

Input

数据的第一行是一个T,表示有T组数据。
每组数据有两个数n(0 <= n < 9973)和B(1 <= B <= 10^9)。

Output

对应每组数据输出(A/B)%9973。

Sample Input

2
1000 53
87 123456789

Sample Output

7922
6060
#include<stdio.h>
typedef long long ll;
ll fast_pow(ll a,ll b,ll mod)
{
	ll res=1;
	while(b)
	{
		if(b&1) res=res*a%mod;
		b>>=1;
		a=a*a%mod;
	}
	return res;
}
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		int n,B,m,ans;
		scanf("%d%d",&n,&B);
		m=fast_pow(B,9971,9973);
		ans=(n*m)%9973;
		printf("%d\n",ans);
	}
	return 0;
}

例题二-3的幂的和

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

Input

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

Output

输出:计算结果

Sample Input

3

Sample Output

40

看做3的等比数列求前N+1项和,再结合快速幂和费马小定理

#include<stdio.h>
#define  LL long long//要省略的在前面 等价于 typedef long long LL;  
int fast_pow(LL a,LL b,LL mod)
{
	LL res=1;
	while(b)
	{
		if(b&1) res=res*a%mod;
		b>>=1;
		a=a*a%mod;
	}
	return res;
}
int main()
{
	int N;
	while(scanf("%d",&N)!=EOF)
	{
		LL j=fast_pow(2,1000000005,1000000007);
		LL k=fast_pow(3,N+1,1000000007);
		LL h=1%1000000007;
		LL r=(k-h)%1000000007;
		LL ans=(r*j)%1000000007;
		printf("%lld\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/vp_death_note/article/details/81185949
今日推荐