Python默尼森数
时间: 2023-12-25 09:28:53 浏览: 121
以下是Python中找第n个默尼森数的例子:
1. 使用第一个引用的定义找第n个默尼森数
```python
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def find_mersenne_number(n):
count = 0
num = 2
mersenne_num = 0
while count < n:
if is_prime(num):
mersenne_num = 2 ** num - 1
if is_prime(mersenne_num):
count += 1
num += 1
return mersenne_num
n = 5
print(f"The {n}th Mersenne number is: {find_mersenne_number(n)}") # 输出:The 5th Mersenne number is: 8191
```
2. 使用第二个引用的定义找第n个默尼森数
```python
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def find_mersenne_number(n):
count = 0
num = 2
mersenne_num = 0
while count < n:
if is_prime(num):
mersenne_num = 2 ** num - 1
if is_prime(mersenne_num):
count += 1
num += 1
return mersenne_num
n = 5
print(f"The {n}th Mersenne number is: {find_mersenne_number(n)}") # 输出:The 5th Mersenne number is: 31
```
阅读全文