結果
問題 |
No.308 素数は通れません
|
ユーザー |
![]() |
提出日時 | 2015-12-01 10:42:48 |
言語 | Java (openjdk 23) |
結果 |
WA
|
実行時間 | - |
コード長 | 1,465 bytes |
コンパイル時間 | 2,371 ms |
コンパイル使用メモリ | 79,756 KB |
実行使用メモリ | 41,508 KB |
最終ジャッジ日時 | 2024-09-14 06:49:36 |
合計ジャッジ時間 | 19,057 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 65 WA * 19 RE * 23 |
ソースコード
package no308; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); if (n < 60) { System.out.println(solveNaive((int) n)); return; } if (n % 8 != 1 || !BigInteger.valueOf(n-8).isProbablePrime(20)) { System.out.println(8); }else{ System.out.println(14); } } public static int solveNaive(int n) { boolean[] isPrime = isPrimeArray(n); for(int w=1;w<=n;w++) { boolean[] used = new boolean[n+1]; Queue<Integer> q = new ArrayDeque<>(); used[1] = true; q.offer(1); while(!q.isEmpty()) { int x = q.poll(); check(x+1,n,isPrime,used,q); check(x-1,n,isPrime,used,q); check(x+w,n,isPrime,used,q); check(x-w,n,isPrime,used,q); } if (used[n]) { return w; } } return -1; } public static void check(int x,int n,boolean[] isPrime,boolean[] used,Queue<Integer> q) { if (x < 1 || x > n || isPrime[x] || used[x]) { return; } used[x] = true; q.offer(x); } public static boolean[] isPrimeArray(int max) { boolean[] isPrime = new boolean[max+1]; Arrays.fill(isPrime, true); isPrime[0] = isPrime[1] = false; for(int i=2;i*i<=max;i++) { if (isPrime[i]) { int j = i * 2; while(j<=max) { isPrime[j] = false; j += i; } } } return isPrime; } }