[英]How to find nth prime number in python without using function code?
我是python的新手,我不知道如何在不使用函數代碼的情況下編寫一個while循環來在python中查找第n個素數。
i=2
N=int(input("Enter a number:"))
count=0
while
if (is prime number):
count=count+1
print("The prime number is:",str(i))
有幾種方法可以做到。 這是一個天真的:
N = int(input("Enter N to get Nth prime: "))
count = 1
prime = 2
while count<N: # find more primes
prime += 1 + prime%2 # next candidate (3,5,... odds)
for divisor in range(3,prime,2): # check if divisible
if prime % divisor == 0: break # not a prime, don't count it
else:
count += 1 # didn't break, it's a prime
print(N,"th prime is ",prime)
使用while循環查找第N個素數
N=int(input("Enter a number:"))
count=0
i=2
cur_prime=0
while not count==N:
j=2
isPrime=True
while j*j<=i:
if i%j==0:
isPrime=False
j=j+1
if isPrime==True:
count=count+1
cur_prime=i
i=i+1
print(f"The {N}th prime number is {cur_prime}")
#Enter a number:5
#The 5th prime number is 11
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.