📜  用于 Zeckendorf 定理的Python程序(非相邻斐波那契表示)

📅  最后修改于: 2022-05-13 01:56:56.380000             🧑  作者: Mango

用于 Zeckendorf 定理的Python程序(非相邻斐波那契表示)

给定一个数字,找到一个数字表示为非连续斐波那契数的总和。

例子:

Input:  n = 10
Output: 8 2
8 and 2 are two non-consecutive Fibonacci Numbers
and sum of them is 10.

Input:  n = 30
Output: 21 8 1
21, 8 and 1 are non-consecutive Fibonacci Numbers
and sum of them is 30.

这个想法是使用贪心算法。

1) Let n be input number

2) While n >= 0
     a) Find the greatest Fibonacci Number smaller than n.
        Let this number be 'f'.  Print 'f'
     b) n = n - f 
Python3
# Python program for Zeckendorf's theorem. It finds representation
# of n as sum of non-neighbouring Fibonacci Numbers.
 
# Returns the greatest Fibonacci Number smaller than
# or equal to n.
def nearestSmallerEqFib(n):
     
    # Corner cases
    if (n == 0 or n == 1):
        return n
        
    # Finds the greatest Fibonacci Number smaller
    # than n.
    f1, f2, f3 = 0, 1, 1
    while (f3 <= n):
        f1 = f2;
        f2 = f3;
        f3 = f1 + f2;
    return f2;
 
 
# Prints Fibonacci Representation of n using
# greedy algorithm
def printFibRepresntation(n):
     
    while (n>0):
 
        # Find the greates Fibonacci Number smaller
        # than or equal to n
        f = nearestSmallerEqFib(n);
  
        # Print the found fibonacci number
        print (f,end=" ")
  
        # Reduce n
        n = n-f
 
# Driver code test above functions
n = 30
print ("Non-neighbouring Fibonacci Representation of", n, "is")
printFibRepresntation(n)


输出:
Non-neighbouring Fibonacci Representation of 30 is
21 8 1

有关更多详细信息,请参阅有关 Zeckendorf 定理(非相邻斐波那契表示)的完整文章!