Description
- 在 ([1,n]) 的区间中找出两个整数 (a,b) 使得 (gcd(a,b)) 最大,求最大的 (gcd(a,b))。
- 多组数据,(1 le t le 100)。
- (2 le n le 10^6)。
Solution 1
直接暴力,但 (10^6) 太大了不能直接 (n^2) 所以循环的第一层在 ([1,n]) 枚举,第二层在 ([i,n]) 枚举。
Code
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int main () {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
int ans = -1;
for (int i = 1; i <= n; i++)
for (int j = i + 1; j <= n; j++)
ans = max(ans, gcd(i, j));
printf("%d
", ans);
}
return 0;
}
预期分数:(30) 到 (70),因为多组数据加上极限数据卡爆掉
Solution 2
经过 我不知道咋搞的 数学推导,我们可以知道输出就是 (dfrac{n}{2}),不难想到其中一种构造就是 (gcdleft(dfrac{n}{2},n
ight))。(如果 (n) 是奇数就下取整)
这个 (O(t)) 做法再不过就 ……
Code
#include <bits/stdc++.h>
using namespace std;
int main () {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
printf("%d
", n / 2);
}
return 0;
}
预期分数:(100)
2020.6.29
By Shuchong