File tree Expand file tree Collapse file tree 1 file changed +56
-5
lines changed
Expand file tree Collapse file tree 1 file changed +56
-5
lines changed Original file line number Diff line number Diff line change 1- # Title : Iterative + recursive Fibonacci
2- # Topic : Basics
3- # Language : java
4- # Example : see bottom
1+ // Metadata Header (MANDATORY)
2+ // -----------------------------
3+ // Program Title: Fibonacci Sequence (Iterative)
4+ // Author: IamBisrutPyne
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: Java
10+ //
11+ // Time Complexity: O(n)
12+ // Space Complexity: O(1)
13+ // -----------------------------
514
6- // Iterative + recursive Fibonacci - placeholder in java
15+ import java .util .ArrayList ;
16+ import java .util .List ;
17+
18+ public class FibonacciIterative {
19+
20+ /**
21+ * Generates the Fibonacci sequence up to the n-th term iteratively.
22+ * Uses long to prevent integer overflow for larger sequences.
23+ *
24+ * @param n The number of terms to generate.
25+ * @return A list of the first n Fibonacci numbers.
26+ */
27+ public static List <Long > generate (int n ) {
28+ if (n < 0 ) {
29+ throw new IllegalArgumentException ("Input must be non-negative." );
30+ }
31+
32+ List <Long > sequence = new ArrayList <>();
33+ if (n == 0 ) return sequence ;
34+
35+ long a = 0 ; // F(0)
36+ long b = 1 ; // F(1)
37+
38+ sequence .add (a );
39+ if (n == 1 ) return sequence ;
40+
41+ sequence .add (b );
42+
43+ for (int i = 2 ; i < n ; i ++) {
44+ long nextVal = a + b ;
45+ sequence .add (nextVal );
46+ // Shift values
47+ a = b ;
48+ b = nextVal ;
49+ }
50+ return sequence ;
51+ }
52+
53+ public static void main (String [] args ) {
54+ int n_terms = 20 ;
55+ System .out .println ("Fibonacci sequence (first " + n_terms + " terms): " + generate (n_terms ));
56+ }
57+ }
You can’t perform that action at this time.
0 commit comments