結果
問題 | No.308 素数は通れません |
ユーザー |
|
提出日時 | 2016-03-14 13:57:29 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 136 ms / 1,000 ms |
コード長 | 1,637 bytes |
コンパイル時間 | 4,257 ms |
コンパイル使用メモリ | 84,204 KB |
実行使用メモリ | 41,812 KB |
最終ジャッジ日時 | 2024-11-27 18:47:15 |
合計ジャッジ時間 | 17,925 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 107 |
ソースコード
import java.util.ArrayDeque; import java.util.Arrays; import java.util.Date; import java.util.Queue; import java.util.Scanner; import java.math.BigInteger; public class main{ public static final BigInteger EIGHT=new BigInteger("8"); public static void main(String[] args){ Scanner sc=new Scanner(System.in); long exec_time=new Date().getTime(); BigInteger n=sc.nextBigInteger(); if(n.compareTo(BigInteger.valueOf(60))<0){ System.out.println(solveNaive(n.intValue())); return; } if(!n.remainder(EIGHT).equals(BigInteger.ONE)||!n.subtract(EIGHT).isProbablePrime(20)){ System.out.println("8"); }else{ System.out.println("14"); } System.err.println(new Date().getTime()-exec_time+"ms"); } 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 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(); if(x%w!=0){ check(x+1,n,isPrime,used,q); } if(x%w!=1){ 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 boolean[] isPrimeArray(int max){ boolean[] isPrime=new boolean[max+1]; Arrays.fill(isPrime, true); for(int i=2;i*i<=max;i++){ int j=i*2; while(j<=max){ isPrime[j]=false; j+=i; } } return isPrime; } }