結果

問題 No.106 素数が嫌い!2
ユーザー htensaihtensai
提出日時 2019-12-30 18:49:56
言語 Java21
(openjdk 21)
結果
AC  
実行時間 1,534 ms / 5,000 ms
コード長 1,629 bytes
コンパイル時間 3,045 ms
コンパイル使用メモリ 79,596 KB
実行使用メモリ 51,240 KB
最終ジャッジ日時 2024-04-26 17:23:58
合計ジャッジ時間 13,313 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 108 ms
40,188 KB
testcase_01 AC 108 ms
40,020 KB
testcase_02 AC 108 ms
40,016 KB
testcase_03 AC 122 ms
41,152 KB
testcase_04 AC 704 ms
48,708 KB
testcase_05 AC 1,534 ms
51,240 KB
testcase_06 AC 1,513 ms
51,048 KB
testcase_07 AC 1,518 ms
50,980 KB
testcase_08 AC 250 ms
45,832 KB
testcase_09 AC 247 ms
45,320 KB
testcase_10 AC 1,500 ms
51,232 KB
testcase_11 AC 700 ms
47,912 KB
testcase_12 AC 1,434 ms
50,916 KB
testcase_13 AC 122 ms
41,404 KB
testcase_14 AC 122 ms
41,132 KB
testcase_15 AC 128 ms
41,344 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        if (k == 1) {
            System.out.println(n - 1);
            return;
        }
        TreeSet<Integer> primes = new TreeSet<>();
        primes.add(2);
        for (int i = 3; i <= n / 2; i += 2) {
            if (isPrime(i, primes)) {
                primes.add(i);
            }
        }
        int count = 0;
        for (int i = 2; i <=n; i++) {
            if (primes.contains(i)) {
                continue;
            }
            if (hasCount(i, k, primes)) {
                count++;
            }
        }
        System.out.println(count);
    }
    
    static boolean hasCount(int x, int k, TreeSet<Integer> primes) {
        int count = 0;
        for (int y : primes) {
            if (Math.sqrt(x) < y) {
                break;
            }
            if (x % y == 0) {
                count++;
                if (count >= k) {
                    return true;
                }
                while (x % y == 0) {
                    x /= y;
                }
            }
        }
        if (x != 1) {
            if (count + 1 >= k) {
                return true;
            }
        }
        return false;
    }
    static boolean isPrime(int x, TreeSet<Integer> primes) {
        for (int y : primes) {
            if (Math.sqrt(x) < y) {
                break;
            }
            if (x % y == 0) {
                return false;
            }
        }
        return true;
    }
}
0