2025-10-07 考场防烫tips P5091
原题链接:P5091 【模板】扩展欧拉定理 - 洛谷
这题就是扩展欧拉定理的模板。
但是,当我打出代码,发现竟然TLE了!
于是我进行了重构,居然过了!!!
原因在于第一版代码使用
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
关闭了流输入,而题目中b很大,所以要使用getchar()读入,然而二者不可以混用!
这是一次教训,好在还没有开赛(不过赛前我为什么要学数论)。
好了,附上正解代码!
#include <bits/stdc++.h>
#define int long long
using namespace std;
int a, m;
int qpow(int x, int y, int p){int res = 1, base = x;while (y){if (y & 1){res = res * base % p;}base = base * base % p;y >>= 1;}return res;
}
int phi(int x){int res = x;for (int i = 2; i * i <= x; i++){if (x % i == 0){while (x % i == 0)x /= i;res = res / i * (i - 1);}}if (x > 1)res = res / x * (x - 1);return res;
}
signed main(){cin >> a >> m;int ph = phi(m);bool flag = 0;char c = getchar();while (!(c >= '0' && c <= '9'))c = getchar();int b = 0;while (c >= '0' && c <= '9'){b = b * 10ll + (c - '0');if (b >= ph){flag = 1;b %= ph;}c = getchar();}if (flag)b += ph;cout << qpow(a, b, m);
}
千万别犯烫了!