计蒜客2019蓝桥杯国赛B组模拟赛题解汇总:
https://blog.csdn.net/daixinliangwyx/article/details/90231587
第四题
标题:公约数
解法:直接暴搜搜k个数肯定是不行的。可以先将每个数的数量记录一下,同时比较出所有数的最大值maxn,因为所有数的最大公约数最大也只能是最大值maxn,所以可以设定i从maxn开始递减遍历到1,然后看i的倍数有没有达到k个(i的倍数的因子肯定包含i),如果达到了,那么这个i就是答案。
坑点:注意看数据范围,有30%的数据可能k>n,这种情况应该输出1的,如果不加以特判是会输出0的。所以可以设定ans初始值为1,遍历i最小到2,当2还不满足时,使用的最大公约数就是1了(最大公约数为1的时候也没必要统计倍数数量了,因为所有数都满足为1的倍数)。
代码:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static InputReader in = new InputReader(new BufferedInputStream(System.in));
public static PrintWriter out = new PrintWriter(System.out);
public static int n, k, maxn, ans;
public static int[] a = new int[1000010];
public static int[] f = new int[1000010];
public static void main(String[] args) {
n = in.nextInt();
k = in.nextInt();
maxn = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
f[a[i]]++;
maxn = Math.max(maxn, a[i]);
}
ans = 1;
for (int i = maxn; i > 1; i--) {
if (getCount(i) == 1) {
ans = i;
break;
}
}
out.println(ans);
out.flush();
out.close();
}
static int getCount(int gcdnum) {
int sum = 0;
for (int i = gcdnum; i <= maxn; i += gcdnum) {
sum += f[i];
if (sum >= k) return 1;
}
return 0;
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
String str = null;
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
}
评测结果: