简体   繁体   English

如何在不使用函数代码的情况下在python中找到第n个素数?

[英]How to find nth prime number in python without using function code?

I'm new to python and I have no idea how to write a while loop 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))

There are several ways to do it.有几种方法可以做到。 Here's a naive one:这是一个天真的:

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)

Finding Nth prime numbers using while loop使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM