题解:P12312 [蓝桥杯 2024 国 C] 六一儿童节

· · 题解

P12312 [蓝桥杯 2024 国 C] 六一儿童节

题目简介:

从 1 到 20240601 中找 x 和 y 两个数,使 x 小于 y,并且 x 的平方加上 y 的平方能被 6421 整除。

思路分析:

最简单的方法,暴力枚举,二重循环,单出来结果要好久,所以启用,但也行。

代码:

#include<bits/stdc++.h>
using namespace std;
#define int long long
int ans = 0;
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    for (int i = 1; i <= 20240601; i++) {
        for (int j = 1; j <= 20240601; j++) {
            if ((i * i + j * j) / 6421 == 0) {
                ans ++;
            }
        }
    }
    cout << ans << endl;
    return 0;
}

然后思考正解。

根据欧拉定理和中国剩余定理,可以发现 n 的平方模 6421 的值由 n 模 6421 和 n 模 6420 来决定,也就是说最大周期为 6421\times 6240,也就是 38943840,直接遍历即可,用快速幂加快速度。

代码:

#include <bits/stdc++.h>
using namespace std;
#define int long long
const int p = 6421;
int ul[20240605],un[6425],ans;
int f(int a, int b) {//快速幂 
    int sum = 1;
    a = a % p;
    while (b > 0) {
        if(b & 1) {
            sum = (sum * a) % p;
        } 
        a = (a * a) % p;
        b = b >> 1;
    }
    return sum % p;
}
signed main() {
    for(int i = 1; i <= 20240601; i++) {
        ul[i] = f(i,i);
    } 
    for(int i = 1; i <= 20240601; i++) {
        ans += un[(6421-ul[i]) % p];
        ++ un[ul[i]];
    }
    cout << ans;
    return 0;
}

因为只要答案,所以超时没事。

最终答案 51349141107。

谢谢观看,求过。