【蓝桥云课刷题(春晚魔术) | 快速幂+费马小定理】

题目:
在这里插入图片描述
一开始看到题目没留意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}ababmod(m1)(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了


如果我的内容对你有帮助,请 点赞 评论 收藏 。创作不易,大家的支持就是我坚持下去的动力!
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青衫码上行

你的鼓励将是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值