我无法打印两对。
当我第一次执行代码时,我认为第一个数字是素数而不是第二个数字。
所以我在printTwinPrimeNumbers(twinPrime)函数中使用了主要检查器并通过它。但现在它说数字2没有定义。
如何检查第一个和第二个数字。
# determine if numbers are prime
def Prime(num1):
divisor = 2
while divisor <= num1 / 2:
if num1 % divisor == 0:
return False # number is not a prime
divisor += 1
return True # number is prime
def printTwinPrimeNumbers(twinPrime):
NUMBER_OF_PRIMES = 50
NUMBER_OF_PRIMES_PER_LINE = 1
num1 = 3 # number to be tested starting point
count = 0
for i in range(0, 1001):
if Prime(num1):
def prime2(num2):
num2 = num1 + 2
count += 1
while divisor <= num2 / 2:
if num2 % divisor == 0:
return False # number is not a prime
divisor += 1
return True # number is prime
if prime2(num2):
print("(", num1, ",", num2, ")", end = '')
# makes sure only one is printed per line
if count % NUMBER_OF_PRIMES_PER_LINE == 0:
# Print the number and advance to the new line
print()
num1 += 1
def main():
print("The Twin Prime Numbers are: ")
printTwinPrimeNumbers(50)
main()# calls main function
答案 0 :(得分:0)
变量num2
未定义,因为它仅在 prime2
中定义,但您将其用作参数 {{1} }。此外,根本不需要prime2
,它与prime2
相同,但具有不同的参数。只需对Prime
和Prime
使用num1
即可。
num2
此外,这非常浪费,因为您正在测试每个数字的素数两次。相反,只需创建该范围内所有素数的列表,并检查每个数字是否为&#34; twin&#34;也在那个名单中。
for i in range(0, 1001):
num1 = i
num2 = i + 2
if Prime(num1) and Prime(num2):
print("(", num1, ",", num2, ")")
答案 1 :(得分:0)
# determine if numbers are prime
def Prime(num1):
divisor = 2
while divisor <= num1 / 2:
if num1 % divisor == 0:
return False # number is not a prime
divisor += 1
return True # number is prime
def printTwinPrimeNumbers(twinPrime):
NUMBER_OF_PRIMES = 50
NUMBER_OF_PRIMES_PER_LINE = 1
num1 = 3 # number to be tested starting point
count = 0
for i in range(0, 1001):
if Prime(num1):
num2 = num1 + 2
def prime2(num2):
count += 1
while divisor <= num2 / 2:
if num2 % divisor == 0:
return False # number is not a prime
divisor += 1
return True # number is prime
if prime2(num2):
print("(", num1, ",", num2, ")", end = '')
# makes sure only one is printed per line
if count % NUMBER_OF_PRIMES_PER_LINE == 0:
# Print the number and advance to the new line
print()
num1 += 1
def main():
print("The Twin Prime Numbers are: ")
printTwinPrimeNumbers(50)
main()# calls main function