結果

問題 No.458 異なる素数の和
ユーザー tenten
提出日時 2020-09-10 15:52:18
言語 Java
(openjdk 23)
結果
AC  
実行時間 193 ms / 2,000 ms
コード長 1,035 bytes
コンパイル時間 2,472 ms
コンパイル使用メモリ 78,952 KB
実行使用メモリ 42,388 KB
最終ジャッジ日時 2024-12-23 10:07:20
合計ジャッジ時間 7,377 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 28
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
	public static void main (String[] args) {
    	Scanner sc = new Scanner(System.in);
    	int n = sc.nextInt();
    	ArrayList<Integer> primes = new ArrayList<>();
    	int[] counts = new int[n + 1];
    	Arrays.fill(counts, -1);
    	counts[0] = 0;
    	for (int i = 2; i <= n; i++) {
    	    if (isPrime(i, primes)) {
    	        primes.add(i);
    	        for (int j = n - i; j >= 0; j--) {
    	            if (counts[j] < 0) {
    	                continue;
    	            }
    	            counts[j + i] = Math.max(counts[j + i], counts[j] + 1);
    	        }
    	    }
    	}
    	if (counts[n] > 0) {
    	    System.out.println(counts[n]);
    	} else {
    	    System.out.println(-1);
    	}
    }
    
    static boolean isPrime(int x, ArrayList<Integer> primes) {
        for (int y : primes) {
            if (y * y > x) {
                break;
            }
            if (x % y == 0) {
                return false;
            }
        }
        return true;
    }
}
0