結果
| 問題 |
No.308 素数は通れません
|
| コンテスト | |
| ユーザー |
ぴろず
|
| 提出日時 | 2015-12-01 10:50:27 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 153 ms / 1,000 ms |
| コード長 | 1,722 bytes |
| コンパイル時間 | 2,185 ms |
| コンパイル使用メモリ | 79,196 KB |
| 実行使用メモリ | 56,284 KB |
| 最終ジャッジ日時 | 2024-11-27 18:11:12 |
| 合計ジャッジ時間 | 17,036 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 107 |
ソースコード
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 final BigInteger EIGHT = new BigInteger("8");
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
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);
}
}
public static int solveNaive(int n) {
boolean[] isPrime = isPrimeArray(n);
for(int w=1;w<=n;w++) {
// System.out.println(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();
// System.out.println(x);
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 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;
}
}
ぴろず