Fastest Approach
Works for only 32 bit signed Integer, as Fibonacci sequence grows exponentially.
Once upon a time, in a land of numbers, there lived a special sequence known as the Fibonacci sequence. This sequence was loved by mathematicians and curious minds alike because it held the secret of how each number could be formed by the sum of the two numbers before it.
In this magical land, the first two numbers were 0 and 1. They were the starting point of the sequence, and they would whisper to each other, “Let’s create more numbers together!” So, they began to work their magic:
- The first number was 0 (let’s call him F0).
- The second number was 1 (we’ll call her F1).
Then, they decided to create the next numbers:
- F2 was born from adding F0 and F1: 0+1=10 + 1 = 10+1=1.
- F3 appeared when they added F1 and F2: 1+1=21 + 1 = 21+1=2.
- F4 came into existence from F2 and F3: 1+2=31 + 2 = 31+2=3.
- This continued until F9 showed up, which was the grand number 34, formed from F7 (13) and F8 (21).
Example 1:
Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Now, to keep track of all these wonderful numbers, they decided to gather in a special list called fib_nums
, where each number would find its place according to its order in the sequence.
So, they arranged themselves like this:
fib_nums = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Each index in this list corresponded to a unique Fibonacci number:
- At index 0, there was 0.
- At index 1, there was 1.
- At index 2, there was 1 again.
- At index 3, the number 2 found its home.
- And so on, all the way to index 9, where 34 resided.
Now, in this land, there was a wise guardian named Solution. She had a special ability to fetch any Fibonacci number with just a magical command.
def fib(self, n):
return self.fib_nums[n]
Whenever someone asked her for the nth Fibonacci number, she would simply look at the fib_nums
list and find the number at position n
.
For instance, if someone wanted to know the number at position 5, Solution would quickly point to 5 in the list and say, “Ah! Here it is!”
And so, the Fibonacci numbers lived happily in their list, always ready to help anyone who sought the secrets of their beautiful sequence, thanks to the wise guardian Solution. The end!
Overall Implementation:
class Solution:
fib_nums = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
def fib(self, n):
return self.fib_nums[n]
# Prompting the user for input
n = int(input("Enter a number: "))
# Creating an instance of Solution and getting the Fibonacci number
solution = Solution()
result = solution.fib(n)
# Printing the result
print("The number is", result)
#Output:
#Enter a number: 3
#The number is 2