备战NOIP——模板复习24

这里只有模板,并不作讲解,仅为路过的各位做一个参考以及用做自己复习的资料,转载注明出处。




逆元

费马小定理

EX-GCD

线性递推




逆元

费马小定理

/*Copyright: Copyright (c) 2018
*Created on 2018-11-07
*Author: 十甫
*Version 1.0 
*Title: 逆元-费马小定理
*Time: 2 mins
*/
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;

inline ll mul(ll a, ll b, ll mod) {
	ll res = 1;
	while(b) {
		if(b & 1) res = ((res % mod) * (a % mod));
		a = ((a % mod) * (a % mod));
		b /= 2;
	}
	return res;
}

int main() {
	ll n, k;
	scanf("%lld%lld", &n, &k);
	printf("%lld\n", mul(n, k - 2, k));
	return 0;
}

EX-GCD

/*Copyright: Copyright (c) 2018
*Created on 2018-11-07
*Author: 十甫
*Version 1.0 
*Title: 逆元-EX-GCD
*Time: 2 mins
*/
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;

inline void exgcd(ll a, ll b, ll &x, ll &y, ll mod) {
	if(!b) {
		x = 1, y = 0;
		return;
	}
	exgcd(b, a % b, y, x, mod);
	y -= (a / b) * x;
	y = (y + mod) % mod;
}

int main() {
	ll n, k;
	scanf("%lld%lld", &n, &k);
	ll a, b;
	exgcd(n, k, a, b, k);
	printf("%lld\n", a);
	return 0;
}

线性递推

/*Copyright: Copyright (c) 2018
*Created on 2018-11-07
*Author: 十甫
*Version 1.0 
*Title: 逆元-线性递推
*Time: inf mins
*/
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int size = 10005;

int inv[size];
inline void make(int n, int p) {
	inv[1] = 1;
	for(int i = 2;i <= n;i++) {
		inv[i] = inv[p % i] * (p - p / i) % p;
	}
}

int main() {
	int n, p;
	scanf("%d%d", &n, &p);
	make(n, p);
	printf("%d\n", inv[n]);
	return 0;
}

 

posted @ 2018-11-07 19:20  十甫  阅读(113)  评论(0编辑  收藏  举报