题解 | #查找组成一个偶数最接近的两个素数#
查找组成一个偶数最接近的两个素数
https://www.nowcoder.com/practice/f8538f9ae3f1484fb137789dec6eedb9
import java.util.Scanner;
/**
* @author hll[yellowdradra@foxmail.com]
* @since 2023-03-16 10:42
**/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
minDiff(in.nextInt());
}
public static void minDiff(int n) {
for (int i = n >> 1; i > 0; i--) {
if (isPrimeQuickly(i) && isPrimeQuickly(n - i)) {
System.out.printf("%s\n%s\n", i, n - i);
break;
}
}
}
public static boolean isPrimeQuickly(int n) {
if (n == 2 || n == 3) {
return true;
}
// 等价于 n % 2 == 0 即n是偶数
if ((n & 1) == 0 || n <= 1) {
return false;
}
int r = n % 6;
if (r != 5 && r != 1) {
return false;
}
int sqrt = (int) Math.sqrt(n);
// 保证i为奇数
for (int i = 5; i <= sqrt; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
}
