题解 | #查找组成一个偶数最接近的两个素数#
查找组成一个偶数最接近的两个素数
https://www.nowcoder.com/practice/f8538f9ae3f1484fb137789dec6eedb9
题解:刚开始的思路是利用穷举法,将小于num的所有素数找出来,然后通过两层循环来遍历查找最接近的两个素数,很笨的方法,实现起来确实有点无脑。在参考了别人的代码后进行了优化,效果稍微能好一些。
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class Main { public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Scanner scanner = new Scanner(br); int num = scanner.nextInt(); int[] result = getTwoClosestPrimesFormAnEven2(num); for (int i = 0; i < result.length; i++) { System.out.println(result[i]); } } // 参考别人的,优化后的方法 private static int[] getTwoClosestPrimesFormAnEven2(int num) { if (num < 4 || num > 1000) return new int[0]; int[] result = new int[2]; int diff = num; for (int i = 2; i <= num / 2; i++) { // 主要是在这里进行了优化 if (isPrime(i) && isPrime(num-i)){ int value1 = i; int value2 = num - i; diff = (value2 -value1) < diff ? value2-value1 : diff; result[0] = value1; result[1] = value2; } } return result; } // 自己写的未进行优化的方法 private static int[] getTwoClosestPrimesFormAnEven1(int num) { if (num < 4 || num > 1000) return new int[0]; int[] result = new int[2]; StringBuilder builder = new StringBuilder(); for (int i = 2; i < num; i++) { if (isPrime(i)) builder.append(i).append(" "); } String[] arr = builder.toString().trim().split(" "); int diff = num; for (int i = 0; i < arr.length-1 ; i++) { for (int j = i; j < arr.length ; j++) { Integer value1 = Integer.valueOf(arr[i]); Integer value2 = Integer.valueOf(arr[j]); if (value1 + value2 == num){ diff = (value2 - value1) < diff ? value2-value1:diff; result[0] = value1; result[1] = value2; } } } return result; } private static boolean isPrime(int num) { boolean flag = true; for (int i = 2; i <= num / 2; i++) { if (num % i == 0) flag = false; } return flag; } }