[英]python program to find the primes in the fibonacci sequence
hello all sorry to be a pain with this one.大家好,很抱歉这一个很痛苦。 I need help with this problem for my coding class, and I can't quite figure out where to go from here.
对于我的编码 class,我需要帮助解决这个问题,而且我无法从这里弄清楚 go 的位置。
Write a function my_n_fib_primes(n) where theoutput fib_primes is a list of the first nnumbers that are both a Fibonacci number and a prime.编写一个 function my_n_fib_primes(n),其中输出 fib_primes 是前 n 个既是斐波那契数又是质数的列表。 Note that 1 is not prime.Test using n = 9.
请注意,1 不是素数。使用 n = 9 进行测试。
the above is what I am supposed to do and so far I have this.以上是我应该做的,到目前为止我有这个。
def my_n_fib_primes(n):
n0=0
n1=1
fib_primes = []
count = 0
while count < n:
count += 1
nth = n0 + n1
n0 = n1
n1 = nth
fib_primes.append(n0)
return fib_primes
my_n_fib_primes(9)
I know I haven't made any real attempt for implementing the primes yet.我知道我还没有真正尝试实现素数。 I just can't quite figure out a way to implement it and only make the count go up when the number is prime.
我只是想不出一种实现它的方法,只有在数字为素数时才计数 go 。
I also already have a code for finding prime numbers that returns the number 1 if the number is prime and 0 if it isn't.我也已经有一个用于查找素数的代码,如果数字是素数,则返回数字 1,如果不是,则返回 0。 that code is this.
该代码是这样的。
def my_is_prime(n):
out = 1
if n > 1:
for i in range(2,n//2):
if (n % i) == 0:
out = 0
else:
out = 1
return out
can someone point me in the right direction?有人能指出我正确的方向吗? thank you.
谢谢你。
Call the prime checker in the loop before adding the number to the list.在将数字添加到列表之前,调用循环中的素数检查器。
def my_n_fib_primes(n):
n0=0
n1=1
fib_primes = []
while len(fib_primes) < n:
nth = n0 + n1
n0 = n1
n1 = nth
if my_is_prime(n0):
fib_primes.append(n0)
return fib_primes
There's no need for the count
variable, just use the length of the result list.不需要
count
变量,只需使用结果列表的长度即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.