#给一个数,判断其是否为素数

素数(质数):在大于1的自然数中,除了1和它本身以外不再有其他因数。


方法一:

num = int(input('输入一个整数:'))
if num < 10 and num != 1:
    if num%2 == 0 or num%3 == 0:
        print(str(num) + '不是素数')
    else:
        print(str(num) + '是素数')
else:
    for i in range(2,int(num**0.5)+1):
        if num%i == 0:
            print(str(num) + '不是素数')
            break
    else:
           print(str(num) + '是素数')



变式:求10万以内的所有素数的数量

方法一:

import datetime
start = datetime.datetime.now()
count = 1
for i in range(3,100000,2):
    if i < 50000:
        for j in range(2,int(i**0.5)+1):
            if i%j == 0:
                break
        else:
            count += 1
    else:
        for j in range(2,int(i**0.5)+1):
            if i%j == 0:
                break
        else:
            count += 1
delta = (datetime.datetime.now() - start).total_seconds()
print(count)
print(delta)


方法二:

import datetime
start = datetime.datetime.now()
count = 1
for i in range(3,100000) :
    for j in range(2,int(i**0.5)+1):
        if i%j == 0 :
            break
    else :
        count += 1
delta = (datetime.datetime.now() - start).total_seconds()
print(count)
print(delta)