結果

問題 No.1657 Sum is Prime (Easy Version)
ユーザー ThetaTheta
提出日時 2024-04-16 18:29:29
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 327 ms / 2,000 ms
コード長 2,136 bytes
コンパイル時間 219 ms
コンパイル使用メモリ 82,304 KB
実行使用メモリ 105,328 KB
最終ジャッジ日時 2024-04-16 18:29:35
合計ジャッジ時間 4,789 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 64 ms
66,048 KB
testcase_01 AC 62 ms
66,432 KB
testcase_02 AC 296 ms
103,584 KB
testcase_03 AC 65 ms
66,432 KB
testcase_04 AC 61 ms
66,304 KB
testcase_05 AC 60 ms
66,412 KB
testcase_06 AC 74 ms
72,832 KB
testcase_07 AC 66 ms
69,376 KB
testcase_08 AC 70 ms
70,272 KB
testcase_09 AC 69 ms
71,808 KB
testcase_10 AC 83 ms
71,552 KB
testcase_11 AC 75 ms
73,856 KB
testcase_12 AC 273 ms
103,564 KB
testcase_13 AC 167 ms
94,172 KB
testcase_14 AC 220 ms
101,028 KB
testcase_15 AC 236 ms
102,036 KB
testcase_16 AC 159 ms
92,800 KB
testcase_17 AC 143 ms
93,440 KB
testcase_18 AC 149 ms
94,208 KB
testcase_19 AC 271 ms
102,380 KB
testcase_20 AC 182 ms
96,220 KB
testcase_21 AC 327 ms
104,832 KB
testcase_22 AC 249 ms
104,960 KB
testcase_23 AC 238 ms
105,328 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from itertools import combinations, count, accumulate, pairwise, product

from collections import defaultdict
from math import ceil, sqrt
from typing import List


def calc_prime_numbers(upper: int) -> List[int]:
    if upper < 2:
        return []
    if upper == 3:
        return [2]
    if upper == 4:
        return [2, 3]
    if 5 <= upper <= 6:
        return [2, 3, 5]
    if 7 <= upper <= 10:
        return [2, 3, 5, 7]
    sqrt_upper = ceil(sqrt(upper))
    primes = []

    prime_flag = [False, True] * (upper // 2 + 1)
    prime_flag[1] = False
    prime_flag[2] = True

    for num in range(3, len(prime_flag)):
        if not prime_flag[num]:
            continue
        if num * 2 >= len(prime_flag):
            continue
        for multi_num in range(num * 2, len(prime_flag), num):
            prime_flag[multi_num] = False
    return (num for num, flag in enumerate(prime_flag) if flag)


def main():
    L, R = map(int, input().split())
    # B-A >= 1のときを考える
    # B-Aが偶数の時、A,A+1,...,Bは全部で奇数個ある
    # この時総和は(A+B)/2 * (B-A+1)の形で表せる
    # (A+B)/2が1になることはこの条件ではないので、確実に総和は合成数
    # またB-Aが奇数の時は、全部で偶数個の要素がある
    # 4の倍数個の要素があるときは、総和は必ず偶数になるため素数にはならない
    # 4n+2個の要素からなるとき、総和は中央2数の平均*(4n+2)
    # (m1+m2)/2*(4n+2)=(m1+m2)*(2n+1)
    # n>=1の時これも合成数 n=0のときのみm1+m2が残って素数である可能性が残る
    # B-A=0のときは、A=B自身が素数であるかどうか
    # よって考えるべきは、A<=x<=Bに含まれる数が素数かどうかと、区間内の連続2数の和が
    # 素数であるかだけ

    primes = set(calc_prime_numbers(R * 2))
    ctr = 0
    for num in range(L, R + 1):
        if num in primes:
            ctr += 1
    for num1, num2 in pairwise(range(L, R + 1)):
        if num1 + num2 in primes:
            ctr += 1
    print(ctr)


if __name__ == "__main__":
    main()
0