我对python很陌生,所以我不完全了解如何使用循环。我目前正在编写一段代码,我必须找到前N个素数。 理想的结果是,如果您输入5,则输出2、3、5、7和11,但是无论我为“ max”输入什么,输出总是以2和3结尾。改善这个?
def send_emails(title,msg):
server = smtplib.SMTP_SSL('smtp.yandex.com.tr', 465)
...
答案 0 :(得分:1)
您只能在min
块中递增else
,也就是说,如果min % c
对于所有c
都不为零,即min
是质数。这意味着代码将无法越过任何复合数字。您可以通过将min=min+1
取消缩进一级来使其与for
和else
对齐来解决此问题。
答案 1 :(得分:1)
number = int(input("Prime numbers between 2 and "))
for num in range(2,number + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
答案 2 :(得分:0)
我想这会有所帮助,让我知道。
number = int(input("How many prime numbers do you want ? "))
cnt = 0
for i in range (1, number+1):
for j in range(1, i+1):
if(i%j == 0):
cnt += 1
if(cnt == 2):
print(i)
cnt = 0
答案 3 :(得分:0)
解决方案:获取第n个质数项。遍历每个自然数以获取素数,并将素数附加到列表中。当列表的长度满足用户第n个素数项时,终止程序。
# Get the number of prime numbers entry.
try:
enterNumber = int(input("List of nth prime numbers: "))
except:
print("The entry MUST be an integer.")
exit()
startNumber = 1
primeList = []
while True:
# Check for the entry to greater than zero.
if enterNumber <= 0:
print("The entry MUST be greater than zero.")
break
# Check each number from 1 for prime unless prime number entry is satisfied.
if startNumber > 1:
for i in range(2,startNumber):
if (startNumber % i) == 0:
break
else:
primeList.append(startNumber)
if (len(primeList) == enterNumber):
print(primeList)
break
else:
startNumber = startNumber + 1
continue
答案 4 :(得分:0)
以下代码将为您提供3到N之间的质数,其中N是来自用户的输入:
number = int(input("Prime numbers between 2, 3 and "))
for i in range(2,number):
for j in range(2,int(i/2)+1):
if i%j==0:
break
else:
if j==int(i/2):
print(i)
您可以看到检查数字i为素数,只需检查数字的可除性,直到n / 2。
答案 5 :(得分:0)
尝试:
n = int(input("First N prime number, N ? "))
p = [2]
c = 2
while len(p) < n:
j = 0
c += 1
while j < len(p):
if c % p[j] == 0:
break
elif j == len(p) - 1:
p.append(c)
j += 1
print(p)
答案 6 :(得分:0)
很简单。检查下面的代码,确定它可以正常工作!
N = int(input('Enter the number: ')
i=1
count=0
while(count<N):
for x in range(i,i+1):
c=0
for y in range(1,x+1):
if(x%y==0):
c=c+1
if(c==2):
print(x)
count=count+1
i=i+1