【题目来源】
https://www.luogu.com.cn/problem/P2613
【题目描述】
给出一个有理数 c=a/b,求 c mod 19260817 的值。
这个值被定义为 bx≡a(mod 19260817) 的解。
【输入格式】
一共两行。
第一行,一个整数 a。
第二行,一个整数 b。
【输出格式】
一个整数,代表求余后的结果。如果无解,输出 Angry!
。
【输入样例】
233
666
【输出样例】
18595654
【数据范围】
对于所有数据,保证 0≤a≤10^10001,1≤b≤10^10001,且 a,b 不同时是 19260817 的倍数。
【算法分析】
● 题意为解同余方程 bx≡a(mod 19260817)。
● 若令 1/b mod p 的值为 x,根据同余方程和乘法逆元的定义,则存在整数 k 使得 bx=1+kp,整理后即得到同余方程 bx≡1(mod p)。根据费马小定理,当 b,p 互质,且 p 是质数的时候,b^(p−1)≡1(mod p)。变形可得 b×b^(p−2)≡1(mod p)。即 b^(p−2) (mod p) 是 1/b mod p 的一个整数解。故据此可得 a/b (mod p)=[(a mod p)×(1/b mod p)] mod p 的解。
● 由于 a/b 可能是超大整数(如 10^10000 量级),需在读入时直接对 19260817 取模,避免高精度计算。因此,需要改造传统的快读(https://blog.csdn.net/hnjzsyjyj/article/details/120131534)为“即时取模”的快读。
“即时取模”的快读是一种在输入大整数时直接进行取模运算的优化技术,常用于处理需要大数运算但最终结果需取模的场景(如数论题目)。其核心思想是在逐位读取数字时同步计算模值,避免存储完整的大数。“即时取模”的快读代码如下所示。
int read() { //fast read
int x=0,f=1;
char c=getchar();
while(c<'0' || c>'9') { //!isdigit(c)
if(c=='-') f=-1;
c=getchar();
}
while(c>='0' && c<='9') { //isdigit(c)
x=(x*10LL+c-'0')%MOD;
c=getchar();
}
return x*f;
}
即时取模的快读与传统的快读相比,只有一行代码不同,即 x=(x*10LL+c-'0')%MOD。
【算法代码一:费马小定理求逆元】
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MOD=19260817;
int read() { //fast read
int x=0,f=1;
char c=getchar();
while(c<'0' || c>'9') { //!isdigit(c)
if(c=='-') f=-1;
c=getchar();
}
while(c>='0' && c<='9') { //isdigit(c)
x=(x*10LL+c-'0')%MOD;
c=getchar();
}
return x*f;
}
LL fastPow(LL a,LL n,LL p) {
LL ans=1;
while(n) {
if(n & 1) ans=ans*a%p;
n>>=1;
a=a*a%p;
}
return ans%p;
}
int main() {
int a=read(),b=read();
if(b==0) cout<<"Angry!"<<endl;
else cout<<a*fastPow(b,MOD-2,MOD)%MOD<<endl;
}
/*
in:
233
666
out:
18595654
*/
【算法代码二:扩展欧几里得算法求逆元】
#include<bits/stdc++.h>
using namespace std;
const int MOD=19260817;
int read() { //fast read
int x=0,f=1;
char c=getchar();
while(c<'0' || c>'9') { //!isdigit(c)
if(c=='-') f=-1;
c=getchar();
}
while(c>='0' && c<='9') { //isdigit(c)
x=(x*10LL+c-'0')%MOD;
c=getchar();
}
return x*f;
}
int exgcd(int a,int b,int &x,int &y) {
if(b==0) {
x=1,y=0;
return a;
}
int d=exgcd(b,a%b,y,x);
y-=a/b*x;
return d;
}
int main() {
int a=read(),b=read();
int x,y;
int d=exgcd(b,MOD,x,y);
if(d!=1) printf("Angry!\n");
else printf("%lld\n", (1LL*a*(x%MOD+MOD)%MOD));
}
/*
in:
233
666
out:
18595654
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/147980706
https://blog.csdn.net/hnjzsyjyj/article/details/120131534
https://www.luogu.com.cn/problem/P2613
https://blog.csdn.net/hnjzsyjyj/article/details/147980706