Skip to content

Commit f2a9436

Browse files
Merge pull request #59 from NotSundarPichai/main
Update fibonacci.go
2 parents bb730bb + 8ac6ba5 commit f2a9436

File tree

1 file changed

+57
-5
lines changed

1 file changed

+57
-5
lines changed

snippets/Basics/go/fibonacci.go

Lines changed: 57 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,58 @@
1-
# Title: Iterative + recursive Fibonacci
2-
# Topic: Basics
3-
# Language: go
4-
# Example: see bottom
1+
// Metadata Header (MANDATORY)
2+
// -----------------------------
3+
// Program Title: Fibonacci Sequence (Iterative)
4+
// Author: ghostrider2606
5+
// Date: 2025-10-11
6+
//
7+
// Description: Generates the Fibonacci sequence up to the n-th term using an iterative approach.
8+
//
9+
// Language: Go
10+
//
11+
// Time Complexity: O(n)
12+
// Space Complexity: O(1)
13+
// -----------------------------
514

6-
// Iterative + recursive Fibonacci - placeholder in go
15+
package main
16+
17+
import "fmt"
18+
19+
// fibonacciIterative generates the first n Fibonacci numbers.
20+
// Uses uint64 for large numbers.
21+
func fibonacciIterative(n int) ([]uint64, error) {
22+
if n < 0 {
23+
return nil, fmt.Errorf("input must be a non-negative integer")
24+
}
25+
if n == 0 {
26+
return []uint64{}, nil
27+
}
28+
if n == 1 {
29+
return []uint64{0}, nil
30+
}
31+
32+
sequence := make([]uint64, n)
33+
sequence[0] = 0
34+
sequence[1] = 1
35+
36+
var a, b uint64 = 0, 1
37+
38+
for i := 2; i < n; i++ {
39+
nextVal := a + b
40+
sequence[i] = nextVal
41+
42+
// Shift values
43+
a = b
44+
b = nextVal
45+
}
46+
return sequence, nil
47+
}
48+
49+
func main() {
50+
n_terms := 20
51+
result, err := fibonacciIterative(n_terms)
52+
53+
if err != nil {
54+
fmt.Println("Error:", err)
55+
} else {
56+
fmt.Printf("Fibonacci sequence (first %d terms): %v\n", n_terms, result)
57+
}
58+
}

0 commit comments

Comments
 (0)