如何编写一个函数 wrong_prime 不带参数并且应该 return 第一个素数 p 其中 q = 2^p - 1 不是素数

How to write a function wrong_prime that takes no arguement and should return the first prime p for which q = 2^p - 1 is not prime

500 years ago it was believed that all numbers q of the form q = 2^p - 1 are prime if p is prime.

Write a function wrong_prime that takes no arguments. It should return the first prime p for which q = 2^p - 1 is not prime.

Hint: this number should be between 10 and 15.

我想出的代码如下但不起作用

def isprime(n):

  if n < 2:

    return False

  elif n == 2:

    return True

  else:

    if n % 2 == 0:

      return False

    for i in range(3,n,2):
      if n % i == 0:
        return False
    return True

def wrong_prime():

  for i in range(1,):

    q = 2**i-1
    if isprime(i) and isprime(q) == False:
        print(q)

输入wrong_function时没有输出

任何人都可以帮助产生一个工作功能吗?

range(1,)range(0, 1),即您只测试 0。如果你想要一个开放式的范围,你可以使用例如while 带有额外计数变量的循环。

def wrong_prime():
  i = 1
  while True:    # fix loop
    q = 2**i-1
    if isprime(i) and isprime(q) == False:
        return i # return p, not print q
    i += 1       # remember to increment manually

或使用 nextitertools.count:

import itertools
def wrong_prime():
    return next(p for p in itertools.count(1) if isprime(p) and not isprime(2**p-1))

(当然,给定"Hint"你也可以只用一个range(10, 16)

另外,请注意函数应该 return p 的值,而你的 prints q。为了测试,调用 print(wrong_prime()) 以查看值。