-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFibNums.java
More file actions
47 lines (42 loc) · 1.34 KB
/
FibNums.java
File metadata and controls
47 lines (42 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// https://practice.geeksforgeeks.org/problems/print-first-n-fibonacci-numbers1002/1/
// Ask why I can't do this with an array
import java.util.*;
public class FibNums {
public static long[] printFibb(int n){
//Your code here
ArrayList<Long> fibNums = new ArrayList<>();
if (n == 1) {
fibNums.add(1L);
}
else if (n >= 2) {
fibNums.add(1L);
fibNums.add(1L);
for (int i = 2; i < n; i++) {
long nextFib = fibNums.get(i - 2) + fibNums.get(i - 1);
fibNums.add(nextFib);
}
}
// convert array list to long[]
long[] result = new long[fibNums.size()];
for (int i = 0; i < fibNums.size(); i++) {
result[i] = fibNums.get(i);
}
return result;
}
public static void main(String[] args) {
int n1 = 5;
long[] result1 = printFibb(n1);
System.out.print("Output1: ");
for (long num : result1) {
System.out.print(num + " ");
}
System.out.println();
int n2 = 10; // Changed to 10 to get more Fibonacci numbers
long[] result2 = printFibb(n2);
System.out.print("Output2: ");
for (long num : result2) {
System.out.print(num + " ");
}
System.out.println();
}
}