0

Background

For a coding activity online, I was asked to create a function that took value and returned true if the product of any two consecutive numbers in the Fibonacci Sequence equal that number1.

Example

An example is 5895, no two numbers multiply to this in the Fibonacci Sequence, but the two numbers that multiply the closest to it while being greater than it are 89 and 144, so you would return [89,144, False].

Problem

But I've run into a problem: my function doesn't work for numbers 1 and 0. You can see that numbers in the Fibonacci sequence both multiply to these two values, but my function returns none.

Question

Does anyone have a fix?

def productFib(prod):
    num = [0]
    n1 = 0
    n2 = 1
    while max(num) < prod: 
        nth = n1 + n2
        n1 = n2
        n2 = nth
        num.append(n1)
    q = 0
    w = 1
    while w+1 < len(num):
        for nums in num:
            if num[q] * num[w] == prod:
                return [num[q], num[w], True]
            if num[q] * num[w] > prod:
                return [num[q], num[w], False] 
            q += 1
            w += 1

1. More: If two consecutive numbers did multiply out to the target number you would return the two numbers and the boolean True (num1, num2, True). If there were not two numbers that multiplied out to the target number, you would return two consecutive numbers from the Fibonacci Sequence that multiplied to the closest number to the target number, the number had to be greater than the target number, and would have to return the boolean False (num1, num2, False).

theX
  • 1,008
  • 7
  • 22

1 Answers1

0

The edits I made fix the function to work for prod=0 and prod=1.

def productFib(prod):
    num = [0]
    n1 = 0
    n2 = 1
    while max(num) <= prod:
        nth = n1 + n2
        n1 = n2
        n2 = nth
        num.append(n1)
    q = 0
    w = 1
    while w+1 <= len(num):
        for nums in num:
            if num[q] * num[w] == prod:
                return [num[q], num[w], True]
            if num[q] * num[w] > prod:
                return [num[q], num[w], False]
            q += 1
            w += 1

I did not check a multitude of inputs, but it seems to work.

From comment: The while loops were not being run. In the case of zero: w+1 was not less than len(num) because both were equal to 2. In the case of one: max(num) was not less than prod as both were 1.

Cresht
  • 1,020
  • 2
  • 6
  • 15
  • 1
    It works perfectly, thanks! I just have one more question thought. I don't simply take another persons code and use it without taking anything from this activity. So, do you have any like shorthand explanation why adding the less than or equal to sign fixed it? –  Jul 04 '20 at 02:06
  • The while loops were not being run. In the case of zero: w+1 was not less than len(num) because both were equal to 2. In the case of one: max(num) was not less than prod as both were 1. – Cresht Jul 04 '20 at 02:11