繁体   English   中英

判断一个数是否为斐波那契数

[英]To find if a number is fibonacci or not

我是一名学生,刚接触 python。 我正在尝试编写一个程序来判断用户输入的数字是否为斐波那契。

num=int(input("Enter the number you want to check\n"))
temp=1
k=0
a=0
summ=0
while summ<=num:
    summ=temp+k
    temp=summ
    k=temp
    if summ==num:
        a=a+1
        print("Yes. {} is a fibonnaci number".format(num))
        break
if a==0:
    print("No. {} is NOT a fibonacci number".format(num))
#The program is working for only numbers upto 2.

你不需要那么多变量。 可以使用单个分配生成斐波那契 integer 序列

a, b = b, a + b

# Short for
#     temp = a
#     a = b
#     b = temp + b 

重复应用按顺序将a设置为模式中的数字。 ab的初始值的选择决定了你得到的确切序列。 斐波那契数是在a = 0b = 1时生成的。

a = 0
b = 1

a, b = 1, 0 + 1  # 0, 1
a, b = 1, 1 + 1  # 1, 2
a, b = 2, 1 + 2  # 2, 3
a, b = 3, 2 + 3  # 3, 5
# etc

(作为另一个示例,如果您以a = 2b = 1开头,则会生成卢卡斯数。)

您需要做的就是在每一步都返回True如果n == a ,迭代直到n > a 如果n不是循环生成的a值之一,您将返回False

n = int(input(...))
a = 0
b = 1
while a <= n:
    if n == a:
        return True
    a, b = b, a + b
return False

我建议这样的事情:

fib_terms = [0, 1]  # first two fibonacci terms

user_input= int(input('Enter the number you want to check\n'))

# Add new fibonacci terms until the user_input is reached
while fib_terms[-1] <= user_input:
    fib_terms.append(fib_terms[-1] + fib_terms[-2])

if user_input in fib_terms:
    print(f'Yes. {user_input} is a fibonacci number.')
else:
    print(f'No. {user_input} is NOT a fibonacci number.')

欢迎来到 python 社区。

在您的代码中, temp表示前一个数字,而k表示temp的前一个数字。 问题是您在将下一个值分配给k之前更改了temp 要解决这个问题,您只需更改第 8 行和第 9 行。在新顺序中,您首先将temp的值分配给k然后summ分配给temp 而已!

我建议你通过这样的列表来做: fib[i] = fib[i-1] + fib[i-2]它会提高你的代码的清晰度。

检查这个:

def fibonacci_list(limit):
    u_n_1 = 1
    u_n_2 = 1
    u_n = 1
    out_list = [u_n]
    while u_n <= limit:
        out_list.append(u_n)
        u_n = u_n_1 + u_n_2
        u_n_2 = u_n_1
        u_n_1 = u_n
    return out_list


def is_fibonacci_number(n):
    if n in fibonacci_list(n):
        return True
    return False


def main():
    n = int(input('Enter a number:'))
    if is_fibonacci_number(n):
        print(str(n) + ' is a fibonacci number ')
    else:
        print(str(n) + ' is not a fibonacci number ')


if __name__ == '__main__':
    main()
bool checkfibonacci(int n)
    {
        int a = 0;
        int b = 1;
        if (n == a || n == b) return true;
        int c = a + b;
        while(c <= n)
        {
            if(c == n) return true;
            a = b;
            b = c;
            c = a + b;
        }
        return false;
    }

像这样的事情会做到这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM