File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
24 - Dynamic Programming Problems/01 - Example | Nth Fibonacci Number Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ int nthFibonacci (int n) {
4+ // Base case: If n is 0, return 0 (F(0) = 0)
5+ if (n == 0 )
6+ return 0 ;
7+
8+ // Base case: If n is 1, return 1 (F(1) = 1)
9+ if (n == 1 )
10+ return 1 ;
11+
12+ // Initialize the first two Fibonacci numbers
13+ int a = 0 ; // F(0)
14+ int b = 1 ; // F(1)
15+
16+ // Variable to store the current Fibonacci number
17+ int m = 0 ;
18+
19+ // Loop from 2 to n to calculate the nth Fibonacci number iteratively
20+ for (int i = 2 ; i <= n; i++) {
21+ // The nth Fibonacci number is the sum of the previous two numbers
22+ m = a + b;
23+
24+ // Update a and b for the next iteration
25+ a = b; // Move to the next value in the sequence
26+ b = m; // Current Fibonacci number becomes the next "b"
27+ }
28+
29+ // Return the nth Fibonacci number
30+ return m;
31+ }
32+ };
You can’t perform that action at this time.
0 commit comments