Home > Software engineering >  Does the number belong in the fibonacci sequence?
Does the number belong in the fibonacci sequence?

Time:11-08

A Ke-number is an integer 10≤n≤99 such that, if we start a Fibonacci sequence with its digits, the sequence contains n.

For example, 47 is a Ke-number because the sequence starts like this: 4,7,11,18,29,47, coming to the number itself.

I'm trying to define the recursive function ke_number that takes a two-digit integer and checks if it is a Ke-number. (True or False)

I got it to work like this:

def ke_number(n):
 n1 = int(str(n)[0])
 n2 = int(str(n)[1])
 return n in [fib(i,n1,n2) for i in range(1,100)]


def fib(n, a, b):
  if n==0 or n==1:
    return b
  return fib(n-1, b, a b)

But as you can see, it's not just one function, it's two. How can I transform this into just one recursive function?

CodePudding user response:

Recursive solution:

Try it online!

def ke_number(n, a = None, b = None):
    if a is None:
        return ke_number(n, n // 10, n % 10)
    if a < n:
        return ke_number(n, b, a   b)
    return a == n

print(ke_number(47))
print(ke_number(46))

Output:

True    # for 47
False   # for 46

With function above if you do:

Try it online!

for i in range(10, 100):
    if ke_number(i):
        print(i)

you'll get all Ke numbers:

14
19
28
47
61
75

CodePudding user response:

As there is already a recursive solution posted by Arty, here is a non recursive one that might be handy (easier to read and does not come with the problems recursive function calls can have, but that really depends on what you want to do in the end)

def ke_test(n):
    a, b = divmod(n, 10)
    while b < n:
        a, b = b, a b
    return b == n
  • Related