Python Fibonacci function How to solve with nonrecursive function

Asked 2 years ago, Updated 2 years ago, 15 views

def fibo(n):
        a = 1
        b = 1

        if n <= 2:
            return 1
        else:
            while n > 2:
                if a <= b:
                    a = a + b
                else:
                    b = a + b       
                return a + b

n = int(input())
x = fibo(n)
print(x)

I want to return the nth Fibonacci number and print it out. It is solved only by variables and while statements without a recursive function A and b are variables to store Fibonacci numbers, and I know how to increase the value of a and b in the when statement, but as n increases, I'm not sure I get the value of those two plus the value.

python

2022-09-21 15:34

1 Answers

I read the Fibonacci sequence properties again and worked on a function, and there was one tricky part of the Fibonacci code without recursion. Compare it to your own code and try to figure out why it works.

def fibo(n) :

    # Defines the default state. Paragraph 0 is 0 and paragraph 1 is 1.
    # Here, b is the "last obtained term" and a is the "second and last obtained term".
    a = 0
    b = 1

    # We are currently in the state of seeking paragraph 1.
    SequenceNo = 1

    # Until b becomes paragraph n:
    while SequenceNo < n :

        # The value before changing b is stored in a separate variable.
        lastB = b

        # Add a to b. Now b is the changed b.
        b += a

        # Change a to b before the change.
        # This way, the b + = a operation works as intended when the next while is executed.
        a = lastB

        # Prepare to deal with the next section.
        SequenceNo += 1

    # Now that we've come this far, b is the value of paragraph n. Print it out and finish.
    return b

# Testing
print(fibo(7)) # 13
print(fibo(12)) # 144


2022-09-21 15:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.