#41671: 0.8s水啦


19552108 (七年九班34號)

學校 : 臺北市立麗山國中
編號 : 278352
來源 : [220.129.198.237]
最後登入時間 :
2024-11-19 19:41:38
a121. 質數又來囉 | From: [1.171.165.81] | 發表日期 : 2024-08-16 10:39

def is_prime(a):
    if a < 2:
        return False
    if a in (2, 3):
        return True
    if a % 2 == 0 or a % 3 == 0:
        return False

    # Miller-Rabin test with specific bases for 32-bit integers
    d, s = a - 1, 0
    while d % 2 == 0:
        d //= 2
        s += 1

    for i in [2, 7, 61]:
        if i >= a:
            continue
        x = pow(i, d, a)
        if x == 1 or x == a - 1:
            continue
        for j in range(s):
            x = pow(x, 2, a)
            if x == a - 1:
                break
        else:
            return False
    return True


while True:
    try:
        a, b = map(int, input().split())
        c = 0
        for i in range(a, b + 1):
            if is_prime(i):
                c += 1
        print(c)
    except EOFError:
        break
 
#41675: Re: 0.8s水啦


19552108 (七年九班34號)

學校 : 臺北市立麗山國中
編號 : 278352
來源 : [220.129.198.237]
最後登入時間 :
2024-11-19 19:41:38
a121. 質數又來囉 | From: [1.171.165.81] | 發表日期 : 2024-08-16 11:03

def is_prime(a):
    if a < 2:
        return False
    if a in (2, 3):
        return True
    if a % 2 == 0 or a % 3 == 0:
        return False

    # Miller-Rabin test with specific bases for 32-bit integers
    d, s = a - 1, 0
    while d % 2 == 0:
        d //= 2
        s += 1

    for i in [2, 7, 61]:
        if i >= a:
            continue
        x = pow(i, d, a)
        if x == 1 or x == a - 1:
            continue
        for j in range(s):
            x = pow(x, 2, a)
            if x == a - 1:
                break
        else:
            return False
    return True


while True:
    try:
        a, b = map(int, input().split())
        c = 0
        for i in range(a, b + 1):
            if is_prime(i):
                c += 1
        print(c)
    except EOFError:
        break

miller rabin是一種無恥快速的解法

 
ZeroJudge Forum