有理数取余

题目

P2613 【模板】有理数取余

解析

简单的数论题
发现并没有对小数取余这一说,所以我们把原式化一下,

\[(c=\frac{a}{b})\equiv a\times b^{-1}(mod\ p)
\]

因为\(p\)是质数,所以我们根据费马小定理\(b^{p-1}\equiv 1(mod p)\)
\(a\times b^{-1}\times 1 \equiv c(mod\ p)\)
\(=>a\times b^{-1}\times b^{p-1} \equiv c(mod\ p)\)
\(=>a\times b^{p-2} \equiv c(mod\ p)\)
于是我们求\(a\times b^{p-2}(mod\ p)\)就好了,注意\(b=0\)时无解。
输入的话根据同余的同加性和同乘性,在读入优化里加一个取余就好了

代码

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int mod = 19260817;
int a, b;

inline int read() {
	int x = 0, f = 0; char ch = getchar();
	while (!isdigit(ch)) f |= (ch == '-'), ch = getchar();
	while (isdigit(ch)) x = (x * 10 + ch - '0') % mod, ch = getchar();
	return f ? -x : x;
}

int qpow(int a, int b) {
	int ans = 1;
	while (b) {
		if (b & 1) ans = (ans * a) % mod;
		a = (a * a) % mod, b >>= 1;
	}
	return ans;
}

main() {
	a = read(), b = read();
	if (b == 0) {
		printf("Angry!");
		return 0;
	}
	cout << (qpow(b, mod - 2) * a % mod + mod) % mod;
}

原文链接: https://www.cnblogs.com/lykkk/p/10902396.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    有理数取余

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/295642

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午5:06
下一篇 2023年2月15日 下午5:06

相关推荐