描述
现在给出你一些数,要求你写出一个程序,输出这些整数相邻最近的素数,并输出其相距长度。如果左右有等距离长度素数,则输出左侧的值及相应距离。
如果输入的整数本身就是素数,则输出该素数本身,距离输出0
如果输入的整数本身就是素数,则输出该素数本身,距离输出0
-
输入
-
第一行给出测试数据组数N(0<N<=10000)
接下来的N行每行有一个整数M(0<M<1000000),
输出
-
每行输出两个整数 A B.
其中A表示离相应测试数据最近的素数,B表示其间的距离。
样例输入
-
3 6 8 10
样例输出
-
5 1 7 1 11 1
code1
import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class Main { private static int[] primes = makePrime(); public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); ArrayList<Integer> list = new ArrayList<Integer>(); while (n-- > 0) { list.add(sc.nextInt()); } for (int num : list) { if (num == 1) { System.out.println(2 + " " + 1); continue; } if (primes[num] == num) { System.out.println(num + " " + 0); } else { int left = num; int right = num; while (primes[left] == 0 && left >= 0) { left--; } while (primes[right] == 0) { right++; } if (left < 0) { System.out.println(right + " " + (right - num)); } else if (num - left <= right - num) { System.out.println(left + " " + (num - left)); } else { System.out.println(right + " " + (right - num)); } } } } public static boolean isPrimeNumFor(int n) { if (n < 2) return false; if (n == 2 || n == 3) return true; if (n%2==0) return false; for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) return false; } return true; } public static int[] makePrime() { int[] result = new int[1000004]; int i = 2; for (i = 2; i <= 1000004; i++) { if (isPrimeNumFor(i)) { result[i] = i; } } return result; } }
code2
import java.util.Scanner; public class Test { static Scanner I = new Scanner(System.in); public static void main(String[] args) { int g = I.nextInt(); while (g-- > 0) { int x = I.nextInt(); for (int i = x, j = x;; i++, j--) { int y = 0; y = Read(j); if (y == 1) { System.out.println(j + " " + ((x - j) > 0 ? (x - j) : -(x - j))); break; } if (i > 0) y = Read(i); if (y == 1) { System.out.println(i + " " + ((x - i) > 0 ? (x - i) : -(x - i))); break; } } } } private static int Read(int n) { int x = 0; if (n == 2 || n == 3 || n == 5) x = 1; if (n > 6) { int y = 1; for (int i = 2; i <= Math.sqrt(n); i++) if (n % i == 0) { y = 0; break; } if (y == 1) x = 1; } return x; } }
边界问题,1和999999的时候要特别注意,999999的时候要计算右侧的最大素数1000003,而不是只计算1000000以内的素数。
如果采用code2就不用关心边界问题了。