标签:range break date second class 为什么 time lse int
#求10万以内所有素数 num = int(input(">>>")) strs = ‘‘ for i in range(2,num): for c in range(2,int(i**0.5)+1): if i%c == 0: break else: strs += str(i)+‘ ‘ print(strs)
方法2:
print(2) for i in range(3,100001,2): if i>10 and i%10 == 5: continue else: for j in range(2,int(i**0.5+1)): if i%j == 0: break else: print(i)
方法3:
#求10万以内所有素数 #此题的目的是为了让大家注意效率问题 #思考:为什么到一个数的一半就可以了 for a in range(2,100000): for b in range(2,int(a**0.5)+1): if a%b == 0: break else: print(a)
方法4:
#求10万以内所有素数 #此题的目的是为了让大家注意效率问题 for a in range(3,100000,2): for b in range(3,int(a**0.5)+1,2): if a%b == 0: break else: print(a)
比较两种算法的效率:
#两种算法的对比的完整代码 import datetime upper_limit = 100000 delta = [0,0] counts = [0,0] start = datetime.datetime.now() for _ in range(10): count[0] = 0 for x in range(2,upper_limit): for i in range(2,int(x**0.5)+1): if x % i == 0: break else: #print(x) counts[0] += 1 delta[0] = (datetime.datetime.now() - start).total_seconds() start = datetime.datetime.now() for _ in range(10): counts[1] = 1 #print(2) for x in range(3,upper_limit,2): for i in range(3,int(x**0.5)+1,2): if x % i == 0: break else: #print(x) counts[1] += 1 delta[1] = (datetime.datetime.now() - start).total_seconds() print(delta, sep="\t") print(conuts, sep="\t")
标签:range break date second class 为什么 time lse int
原文地址:https://www.cnblogs.com/KunGe-13/p/10204991.html