Skip to content

Commit 95ddf63

Browse files
committed
fibbonacci sum solution added
1 parent 7e01b68 commit 95ddf63

File tree

3 files changed

+282
-10
lines changed

3 files changed

+282
-10
lines changed
Lines changed: 273 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
1+
---
2+
id: fibonacci-sum
3+
title: Fibonacci Sum (Geeks for Geeks)
4+
sidebar_label: 0004 - Fibonacci Sum
5+
tags:
6+
- intermediate
7+
- Fibonacci
8+
- Dynamic Programming
9+
- Mathematics
10+
- Algorithms
11+
---
12+
13+
This tutorial contains a complete walk-through of the Fibonacci Sum problem from the Geeks for Geeks website. It features the implementation of the solution code in three programming languages: Python, C++, and Java.
14+
15+
## Problem Description
16+
17+
Given a positive number N, find the value of f0 + f1 + f2 + ... + fN where fi indicates the ith Fibonacci number. Note that f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5, and so on. Since the answer can be very large, return the result modulo 1000000007.
18+
19+
## Examples
20+
21+
```
22+
**Example 1:**
23+
24+
Input:
25+
N = 3
26+
Output:
27+
4
28+
Explanation:
29+
0 + 1 + 1 + 2 = 4
30+
```
31+
32+
```
33+
**Example 2:**
34+
35+
36+
Input:
37+
N = 4
38+
Output:
39+
7
40+
Explanation:
41+
0 + 1 + 1 + 2 + 3 = 7
42+
43+
```
44+
45+
## Your Task
46+
47+
You don't need to read input or print anything. Your task is to complete the function `fibSum()` which takes an integer N as input parameter and returns the sum of all the Fibonacci numbers from f0 to fN.
48+
49+
Expected Time Complexity: $O(LogN)$
50+
Expected Auxiliary Space: $O(1)$
51+
52+
## Constraints
53+
54+
1. $1 \leq N \leq 100000$
55+
56+
## Solution Approach
57+
58+
### Brute Force Approach
59+
60+
#### Intuition:
61+
62+
We can compute the sum of Fibonacci numbers from f0 to fN using a simple iterative method by adding up all Fibonacci numbers up to N.
63+
64+
#### Implementation:
65+
66+
1. Initialize `sum` to 0.
67+
2. Use a loop to compute Fibonacci numbers up to N.
68+
3. Add each Fibonacci number to `sum`.
69+
4. Return the sum modulo 1000000007.
70+
71+
#### Code (C++):
72+
73+
```cpp
74+
#include <iostream>
75+
#define MOD 1000000007
76+
using namespace std;
77+
78+
class Solution {
79+
public:
80+
int fibSum(int N) {
81+
if (N == 0) return 0;
82+
long long f0 = 0, f1 = 1, sum = 1;
83+
for (int i = 2; i <= N; ++i) {
84+
long long f2 = (f0 + f1) % MOD;
85+
sum = (sum + f2) % MOD;
86+
f0 = f1;
87+
f1 = f2;
88+
}
89+
return sum;
90+
}
91+
};
92+
```
93+
94+
### Complexity
95+
96+
- Time Complexity: $O(N)$, as we are iterating from 0 to N.
97+
- Space Complexity: $O(1)$, as we are using a constant amount of extra space.
98+
99+
## Matrix Exponentiation Approach
100+
101+
#### Intuition:
102+
103+
To efficiently find the sum of the first N Fibonacci numbers, we use matrix exponentiation. By utilizing the transformation matrix and its properties, we can compute the required sum in logarithmic time.
104+
105+
#### Implementation:
106+
107+
1. Define a function to multiply two matrices.
108+
2. Define a function to compute the power of a matrix.
109+
3. Use the power function to compute the matrix exponentiation result.
110+
4. Extract the result from the matrix to get the sum of the first N Fibonacci numbers.
111+
112+
#### Code (C++):
113+
114+
```cpp
115+
#include <vector>
116+
using namespace std;
117+
118+
class Solution {
119+
public:
120+
const int mod = 1e9 + 7;
121+
122+
vector<vector<long long int>> multiply(vector<vector<long long int>>& a, vector<vector<long long int>>& b) {
123+
long long int n = a.size();
124+
vector<vector<long long int>> ans(n, vector<long long int>(n, 0));
125+
for (int i = 0; i < n; i++) {
126+
for (int j = 0; j < n; j++) {
127+
for (int k = 0; k < n; k++) {
128+
ans[i][j] = (ans[i][j] + (a[i][k] * b[k][j]) % mod) % mod;
129+
}
130+
}
131+
}
132+
return ans;
133+
}
134+
135+
vector<vector<long long int>> power(vector<vector<long long int>>& F, long long int n) {
136+
if (n == 0) {
137+
long long int s = F.size();
138+
vector<vector<long long int>> ans(s, vector<long long int>(s, 0));
139+
for (int i = 0; i < s; i++) {
140+
ans[i][i] = 1;
141+
}
142+
return ans;
143+
}
144+
if (n == 1) {
145+
return F;
146+
}
147+
vector<vector<long long int>> temp = power(F, n / 2);
148+
vector<vector<long long int>> ans = multiply(temp, temp);
149+
if (n % 2 != 0) {
150+
ans = multiply(ans, F);
151+
}
152+
return ans;
153+
}
154+
155+
long long int fibSum(long long int N) {
156+
vector<vector<long long int>> a = {{1, 1, 1}, {0, 1, 1}, {0, 1, 0}};
157+
vector<vector<long long int>> ans = power(a, N);
158+
return ans[0][2];
159+
}
160+
};
161+
```
162+
163+
#### Code (Python):
164+
165+
```python
166+
class Solution:
167+
MOD = int(1e9 + 7)
168+
169+
def multiply(self, a, b):
170+
n = len(a)
171+
ans = [[0] * n for _ in range(n)]
172+
for i in range(n):
173+
for j in range(n):
174+
for k in range(n):
175+
ans[i][j] = (ans[i][j] + a[i][k] * b[k][j]) % self.MOD
176+
return ans
177+
178+
def power(self, F, n):
179+
if n == 0:
180+
s = len(F)
181+
ans = [[0] * s for _ in range(s)]
182+
for i in range(s):
183+
ans[i][i] = 1
184+
return ans
185+
if n == 1:
186+
return F
187+
temp = self.power(F, n // 2)
188+
ans = self.multiply(temp, temp)
189+
if n % 2 != 0:
190+
ans = self.multiply(ans, F)
191+
return ans
192+
193+
def fibSum(self, N):
194+
a = [[1, 1, 1], [0, 1, 1], [0, 1, 0]]
195+
ans = self.power(a, N)
196+
return ans[0][2]
197+
198+
# Example usage:
199+
solution = Solution()
200+
print(solution.fibSum(5)) # Output the sum of the first 5 Fibonacci numbers
201+
```
202+
203+
#### Code (Java):
204+
205+
```java
206+
import java.util.Arrays;
207+
208+
class Solution {
209+
private static final int MOD = 1000000007;
210+
211+
private long[][] multiply(long[][] a, long[][] b) {
212+
int n = a.length;
213+
long[][] ans = new long[n][n];
214+
for (int i = 0; i < n; i++) {
215+
for (int j = 0; j < n; j++) {
216+
for (int k = 0; k < n; k++) {
217+
ans[i][j] = (ans[i][j] + a[i][k] * b[k][j]) % MOD;
218+
}
219+
}
220+
}
221+
return ans;
222+
}
223+
224+
private long[][] power(long[][] F, long n) {
225+
int size = F.length;
226+
long[][] ans = new long[size][size];
227+
for (int i = 0; i < size; i++) {
228+
ans[i][i] = 1;
229+
}
230+
if (n == 0) return ans;
231+
if (n == 1) return F;
232+
233+
long[][] temp = power(F, n / 2);
234+
ans = multiply(temp, temp);
235+
if (n % 2 != 0) {
236+
ans = multiply(ans, F);
237+
}
238+
return ans;
239+
}
240+
241+
public long fibSum(long N) {
242+
long[][] a = {{1, 1, 1}, {0, 1, 1}, {0, 1, 0}};
243+
long[][] ans = power(a, N);
244+
return ans[0][2];
245+
}
246+
247+
public static void main(String[] args) {
248+
Solution solution = new Solution();
249+
System.out.println(solution.fibSum(5)); // Output the sum of the first 5 Fibonacci numbers
250+
}
251+
}
252+
```
253+
254+
#### Complexity:
255+
256+
- Time Complexity: $O(logN)$, due to matrix exponentiation.
257+
- Space Complexity: $O(logN)$, for recursive stack
258+
259+
## Conclusion
260+
261+
The problem of finding the sum of the first N Fibonacci numbers can be efficiently solved using matrix exponentiation, reducing the time complexity to logarithmic time $O(\log N)$. This approach ensures that even for large values of N, the computation remains feasible and efficient. The provided implementations in C++, Java, and Python demonstrate the versatility of the matrix exponentiation technique across different programming languages.
262+
263+
By leveraging the properties of Fibonacci numbers and matrix multiplication, we can achieve optimal performance for this problem, making it suitable for large input sizes as specified in the constraints.
264+
265+
## References
266+
267+
- **GeeksforGeeks Problem:** [Geeks for Geeks Problem](https://www.geeksforgeeks.org/problems/fibonacci-sum/0)
268+
- **Solution Link:** [Fibonacci Sum on Geeks for Geeks](https://www.geeksforgeeks.org/problems/fibonacci-sum/0)
269+
- **Authors GeeksforGeeks Profile:** [Vipul](https://www.geeksforgeeks.org/user/lakumvipwjge/)
270+
271+
```
272+
This structured tutorial provides a comprehensive solution to the Fibonacci Sum problem, making it easy for others to understand and implement in various programming languages.
273+
```

package-lock.json

Lines changed: 6 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
"clsx": "^2.0.0",
4040
"docusaurus2-dotenv": "^1.4.0",
4141
"express": "^4.18.2",
42+
"framer-motion": "^11.2.10",
4243
"joi": "^17.12.1",
4344
"passport": "^0.7.0",
4445
"passport-github": "^1.1.0",
@@ -61,8 +62,7 @@
6162
"devDependencies": {
6263
"@docusaurus/module-type-aliases": "^3.3.2",
6364
"@docusaurus/types": "^3.3.2",
64-
"dotenv": "^16.4.5",
65-
"framer-motion": "^11.2.10"
65+
"dotenv": "^16.4.5"
6666
},
6767
"browserslist": {
6868
"production": [
@@ -79,4 +79,4 @@
7979
"engines": {
8080
"node": ">=18.0"
8181
}
82-
}
82+
}

0 commit comments

Comments
 (0)