本文介绍了查找第n个素数的程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用python写了一个代码来查找第n个素数.

I wrote a code in python to find the nth prime number.

print("Finds the nth prime number")
def prime(n):
    primes = 1
    num = 2
    while primes <= n:
            mod = 1
            while mod < (num - 1):
                    ptrue = 'true'
                    if num%(num-mod) == 0:
                            ptrue = 'false'
                            break
                    mod += 1
            if ptrue == 'true':
                    primes += 1
    return(num)
nth = int(input("Enter the value of n: "))
print(prime(nth)

代码对我来说看起来不错,但是在我运行它时会返回错误:

The code looked fine to me, but it returns an error when I run it:

  Traceback (most recent call last):
  File "C:/Users/AV/Documents/Python/nth Prime.py", line 17, in <module>
  print(prime(nth))
  File "C:/Users/AV/Documents/Python/nth Prime.py", line 13, in prime
  if ptrue == 'true':
  UnboundLocalError: local variable 'ptrue' referenced before assignment

在我看来,似乎是想说我在最后一行中指的是ptrue,即使我不是.这是什么问题...任何人都可以帮忙吗?

It appears to me as if it is trying to say that I am referring to ptrue in the last line even though I am not. What is the problem here... Can anyone help?

推荐答案

如何使用Boolean?并从while loop

print("Finds the nth prime number")
def prime(n):
    primes = 1
    num = 2
    while primes <= n:
            mod = 1
            ptrue = True
            while mod < (num - 1):
                    if num%(num-mod) == 0:
                            ptrue = False
                            break
                    mod += 1
            if ptrue == True:
                    primes += 1
    return(num)
nth = int(input("Enter the value of n: "))

print prime(nth)

这篇关于查找第n个素数的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 23:36