赞
踩
封装方法:
def is_prime(num):
if not isinstance(num,int):
return False
for i in range(2,num):
if num%i == 0:
return False
return True
print(is_prime(13))
print(is_prime(101))
print(is_prime(10))
不封装方法:
input_num =int( input("请输入数字:"))
for i in range(2,input_num):
if input_num % i ==0:
print(input_num,"is not a prime num!")
break
else:
print(input_num,"is a prime number!")
input_num =int( input("请输入数字:"))
if input_num==1:
print(input_num,"is not a prime number!")
if input_num==2:
print(input_num,"is a prime number!")
for i in range(2,input_num):
if input_num % i ==0:
print(input_num,"is not a prime num!")
break
if i == input_num-1:
print(input_num,"is a prime number!")
用math.sqrt方法来判断素数:
import math
def is_prime(num):
if not isinstance(num,int):
return False
for i in range(2,int(math.sqrt(num)+1)):
if num%i == 0:
return False
return True
print(is_prime(13))
print(is_prime(101))
print(is_prime(10))
用math.sqrt方法来判断素数:
import math def is_prime(num): if not isinstance(num,int): return False if num ==1: return False if num == 2: return True for i in range(2,int(math.sqrt(num)+1)): if num%i == 0: return False return True result = 0 for i in range(1,101): if is_prime(i): result+=i print(i) print(result)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。