The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.
Given n, calculate F(n).
Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Input: n = 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
Input: n = 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
The Fibonacci sequence follows a simple recurrence: F(n) = F(n-1) + F(n-2) with base cases F(0)=0 and F(1)=1. For n up to 30, we can compute F(n) efficiently by iteratively updating the last two values.
a = 0 (F(0)) and b = 1 (F(1)).n iterations: in each, set a to the old b and b to the sum of the old a and b.a holds F(n). Print a.#include <iostream>
class Solution {
public:
void fibonacci(int n) {
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
int c = a + b;
a = b;
b = c;
}
std::cout << a;
}
};
class Solution {
public void fibonacci(int n) {
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
int c = a + b;
a = b;
b = c;
}
System.out.print(a);
}
}
class Solution:
def fibonacci(self, n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
print(a, end='')
class Solution {
fibonacci(n) {
let a = 0, b = 1;
for (let i = 0; i < n; i++) {
[a, b] = [b, a + b];
}
process.stdout.write(a.toString());
}
}
Time Complexity: O(n), as we perform exactly n iterations to compute F(n).
Space Complexity: O(1), using only two variables regardless of input size.
Your notes are automatically saved in your browser's local storage and will persist across sessions on this device.