結果

問題 No.843 Triple Primes
ユーザー tenten
提出日時 2020-08-31 22:57:32
言語 Java
(openjdk 23)
結果
AC  
実行時間 265 ms / 2,000 ms
コード長 1,034 bytes
コンパイル時間 3,199 ms
コンパイル使用メモリ 86,580 KB
実行使用メモリ 44,556 KB
最終ジャッジ日時 2024-11-17 02:45:05
合計ジャッジ時間 13,562 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 42
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
	public static void main (String[] args) {
    	Scanner sc = new Scanner(System.in);
    	int n = sc.nextInt();
    	if (n == 1) {
    	    System.out.println(0);
    	    return;
    	}
    	TreeSet<Integer> primes = new TreeSet<>();
    	for (int i = 2; i <= n; i++) {
    	    if (isPrime(primes, i)) {
    	        primes.add(i);
    	    }
    	}
    	long total = -1;
    	for (int x : primes) {
    	    if (primes.contains(getNum(x + 2))) {
    	        total += 2;
    	    }
    	}
    	System.out.println(total);
    }
    
    static int getNum(int x) {
        int ans = (int)Math.sqrt(x);
        if (ans * ans == x) {
            return ans;
        } else {
            return 0;
        }
    }
    
    static boolean isPrime(TreeSet<Integer> primes, int x) {
        for (int y : primes) {
            if (y * y > x) {
                break;
            }
            if (x % y == 0) {
                return false;
            }
        }
        return true;
    }
    
}
0