![]() |
VOOZH | about |
Given two integers A and B which are the first two terms of the series and another integer N. The task is to find the Nth number using Fibonacci rule i.e. fib(i) = fib(i - 1) + fib(i - 2)
Example:
Input: A = 2, B = 3, N = 4
Output: 8
The series will be 2, 3, 5, 8, 13, 21, ...
And the 4th element is 8.
Input: A = 5, B = 7, N = 10
Output: 343
Approach: Initialize variable sum = 0 that stores sum of the previous two values. Now, run a loop from i = 2 to N and for each index update value of sum = A + B and A = B, B = sum. Then finally, return the sum which is the required Nth element.
Below is the implementation of the above approach:
343
Time Complexity: O(N)
Auxiliary Space: O(1)