显示 python 中的 10 个第一个斐波那契数列

Showing the 10 first prime Fibonacci numbers in python

我的大学需要解决一个问题,我们需要按升序打印 10 个最小的斐波那契素数 order.So 到目前为止,我已经找到了这段代码,但打印它们大约需要 2 分钟想知道是否有更快的打印方式。

import math


def isSquare(n):
    sr = (int)(math.sqrt(n))
    return (sr * sr == n)


def printPrimeAndFib(n):
    prime = [True] * (n + 1)
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p = p + 1
    list=[]
    for i in range(2, n + 1):
        if (prime[i] and (isSquare(5 * i * i + 4) > 0 or
                          isSquare(5 * i * i - 4) > 0)):
            list.append(i)
    print(list)


n = 500000000
printPrimeAndFib(n)

此方法生成斐波那契数,直到找到 10 个素数;大约需要 0.001-0.002 秒

from math import sqrt

def isprime(x):

    #deal with prime special cases 1 and 2
    if x==2:
        return True
    if x == 1 or x%2==0:
        return False

    #Fast-ish prime checking - only scan odds numbers up to sqrt(x)    
    for n in range(3,int(sqrt(x))+1,2):
        if x%n==0:
            return False

    return True

fib_primes = []
current=1
previous=1

while (len(fib_primes)<10):

    if isprime(current):
        fib_primes.append(current)
      

    next = current+previous
    previous = current
    current = next

print(fib_primes)

使用斐波那契生成器和素数过滤器。大约需要 0.002 秒。

from itertools import islice
from math import isqrt

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

def is_prime(n):
    return n > 1 and all(map(n.__mod__, range(2, isqrt(n) + 1)))

fibonacci_primes = filter(is_prime, fibonacci())
print(list(islice(fibonacci_primes, 10)))

输出:

[2, 3, 5, 13, 89, 233, 1597, 28657, 514229, 433494437]