File tree Expand file tree Collapse file tree 1 file changed +57
-5
lines changed
Expand file tree Collapse file tree 1 file changed +57
-5
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments