prime = [2]
while len(prime) <= 1000:
i=3
a = 0
for number in prime:
testlist= []
testlist.append(i%number)
if 0 in testlist:
i=i+1
else:
prime.append(i)
i=i+1
print(prime[999])
[尝试制作一个计算在线课程素数的程序。该程序永远不会结束,但是我看不到代码中的无限循环。
素数是只能被其自身除以一个的数。
我的逻辑是,如果数字可以除以前面的质数,那么它就不是质数。
正如您对问题的评论所指出的,您的代码中存在多个错误。
这是您的代码正常工作的版本。
prime = [2]
i = 3
while len(prime) <= 1000:
testlist = []
for number in prime:
testlist.append(i % number)
if 0 not in testlist:
prime.append(i)
i = i + 1
print prime
我尚未测试,但是您可以创建如下所示的方法:
def get_prime_no_upto(number):
start = 2
primes = list(range(start,number)).to_a
for no in range(start,number):
for num in range(start,no):
if ( no % num == 0) and (num != no):
primes.delete(no)
break
primes
并且可以像使用它
print primeno(100)
欢呼!
我编写了可以帮助您的代码。
import math
import time
start=time.perf_counter()#starting timer
try:
x=int(input('Please enter a number:'))#asking for input
print('')#spacing
b=x % 2#checking divisibility
l=x % 3
f=x % 5
c=x % 7
if x==2 or x==3 or x==5 or x==7:
message='The number %s is prime!'#telling if prime
print(message % x)
elif f==0 or c==0:
message='The number %s is not prime'
print(message % x)
elif x==0:
print('0 is not prime by definition!')
elif x==1:
print('1 is not prime by definition!')
elif x<2:
print('please enter a positive number greater than one')#error statement
elif b==0 or l==0:
message='The number %s is not prime'
print(message % x)
else:
message='The number %s is prime!'
print(message % x)
except Exception:
print('please enter a valid number')#error statement
finally:
print(' ')
print('Prime numbers are positive non-zero numbers that have exactly two factors')
end=time.perf_counter()#ending timer
final_time=end-start
final_time=math.floor(final_time)#rounding
if final_time==1:
message='The time taken is about %s second'#if statement deciding what it will show
print('')
print(message % final_time)
else:
message='The time taken is about %s seconds'
print('')
print(message % final_time)
谢谢,Anikait Sota(中环)