To solve this problem, we need to compute the nth Fibonacci number based on the given sequence pattern. The sequence follows the Fibonacci series where each number is the sum of the two preceding ones, starting from 1 and 1.
Approach
The Fibonacci sequence for this problem is defined as:
- Fib(1) = 1
- Fib(2) = 1
- Fib(n) = Fib(n-1) + Fib(n-2) for n > 2
We use an iterative approach to compute the Fibonacci number efficiently, avoiding the stack overflow issues associated with recursive methods. This approach runs in O(n) time complexity, which is optimal for this problem.
Solution Code
def compute_fibonacci(n):
if n <= 1:
return n
a, b = 1, 1
for _ in range(2, n):
a, b = b, a + b
return b
# Example usage:
# print(compute_fibonacci(2)) # Output: 1
# print(compute_fibonacci(3)) # Output: 2
# print(compute_fibonacci(4)) # Output: 3
# print(compute_fibonacci(5)) # Output:5
# print(compute_fibonacci(6)) # Output:8
Explanation
- Base Cases: For n=1 or n=2, the result is directly 1.
- Iterative Calculation: We initialize two variables
aandbto 1 (representing Fib(1) and Fib(2)). For each number from 3 to n, we updateaandbsuch thatatakes the value ofbandbtakes the sum of the previousaandb. This way, we build up the Fibonacci sequence up to the nth term.
This method efficiently computes the desired Fibonacci number with minimal computational overhead, making it suitable for most practical values of n. If very large values of n (like 1e18) are required, we can switch to faster methods like matrix exponentiation, but the iterative approach works well for typical problem constraints.


(免责声明:本文为本网站出于传播商业信息之目的进行转载发布,不代表本网站的观点及立场。本文所涉文、图、音视频等资料的一切权利和法律责任归材料提供方所有和承担。本网站对此资讯文字、图片等所有信息的真实性不作任何保证或承诺,亦不构成任何购买、投资等建议,据此操作者风险自担。) 本文为转载内容,授权事宜请联系原著作权人,如有侵权,请联系本网进行删除。