题目:
一开始看到题目没留意n的数据范围,只注意到了只有103个测试点,就暴力模拟了一手
#include<iostream>
using namespace std;
#define int long long
#define endl '\n'
#define mod 1000000007
void solve() {
int a, b, c, d;
cin >> a >> b >> c >> d;
while (d--) {
int aa = a, bb = b, cc = c;
a = cc * bb % mod;
b = aa * cc % mod;
c = aa * bb % mod;
}
cout << (a * b) % mod * c % mod << endl;
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
😒 然后直接就超时了,ho li shit,这是突然醒悟,注意到n为109,暴力跑必定会TLE,在纸上模拟了几下之后,发现所求答案其实就是 (A×B×C)2Nmod (109+7)(A \times B \times C)^{2^N} \mod (10^9 + 7)(A×B×C)2Nmod(109+7),直接拿出快速幂,非常好,感觉正解已经呼之欲出了,
#include<iostream>
using namespace std;
#define int long long
#define endl '\n'
#define mod 1000000007
int fastpow(int a, int n) {
long long ans = 1;
while (n) {
if (n & 1) {
ans = (ans * a) % mod;
}
n = n >> 1;
a = (a * a) % mod;
}
return ans;
}
void solve() {
int a, b, c, d;
cin >> a >> b >> c >> d;
d = fastpow(2, d);
cout << fastpow(a * b % mod * c % mod, d) % mod << endl;
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
一看结果,并没有超时,但是显示答案全错 。。。😒
再次检查代码,思路并没有问题,那就是细节问题,思来想去,发现问题应该是出在了 (A×B×C)2N(A \times B \times C)^{2^N}(A×B×C)2N这里,指数的大小为2n,指数增长过快,n稍微大一点就会爆掉了。。。这个时候就思考如何处理指数,上网检索,发现可以使用费马小定理实现指数降幂
费马小定理引入
核心:若 m是质数,且 a不是 m的倍数,则有 ab≡ab mod (m−1)(modm)a^b \equiv a^{b \bmod (m - 1)} \pmod{m}ab≡abmod(m−1)(modm)
那让我们掏出 费马小定理+快速幂 解决它
#include<iostream>
using namespace std;
#define int long long
#define endl '\n'
#define mod 1000000007
int fastpow(int a, int n) {
int ans = 1;
while (n) {
if (n&1) {
ans = (ans * a) % mod;
}
n >>= 1;
a = (a * a) % mod;
}
return ans;
}
//费马小定理给指数降幂
int lowpow(int a, int n) {
int ans = 1;
while (n) {
if (n & 1) {
ans = (ans * a) % (mod - 1);
}
n >>= 1;
a = (a * a) % (mod - 1);
}
return ans;
}
void solve() {
int a, b, c, d;
cin >> a >> b >> c >> d;
d = lowpow(2, d); //费马小定理给指数降幂
cout << fastpow((a * b) % mod * c % mod, d) % mod << endl;
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
很好,AC了
如果我的内容对你有帮助,请 点赞 , 评论 , 收藏 。创作不易,大家的支持就是我坚持下去的动力!