Join Regular Classroom : Visit ClassroomTech

Longest Fibonacci Series – Infytq 2019 Solve

Problem: We have to find the longest X (Fibonacci) series in the given array.

X series – Where the sum of two numbers is the next immediate number.
Example : 2, 6, 8, 14. Explanation: 2+6 = 8 (which is the next immediate number after 6) then 8+6 = 14 (which is the next immediate number after 8)

Sample Input:

(2,6,3,5,8,9)

Sample Output:

(2,3,5,8)

Explanation: There are two possible series (2, 3, 5), (2, 3, 5, 8). As (2, 3, 5, 8) is the largest so it will be desired output.

Solution: We strongly recommend you to try the problem first before moving to the solution.

Python

# Code to understand longest Fibonacci series problem
# www.codewindow.in

list_num=list(map(int, input().split(',')))
length = len(list_num)
total=[]

for i in range (0, length):
    for x in range (i+1, length):
        first = list_num[i]
        second = list_num[x]
        fab = []
        fab.append(first)
        fab.append(second)
        for y in range (x+1, length):
            if (first+second==list_num[y]):
                fab.append(list_num[y])
                first=second
                second=list_num[y]
        if len(total)<len(fab):
            total=fab
if len(total)>2:
    print(tuple(total))
else:
    print("-1")

Input:

(2,6,3,5,8,9)

Output:

(2,3,5,8)

Follow Us

You Missed