-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFibonacci.java
More file actions
86 lines (78 loc) · 2.31 KB
/
Copy pathFibonacci.java
File metadata and controls
86 lines (78 loc) · 2.31 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
// Scanner object to take input from standard input stream
Scanner scanner = new Scanner(System.in);
// Taking input of limit of series will be printed
System.out.println("Enter the limit of fibonacci series:");
int limit = scanner.nextInt();
if (limit <= 0) {
System.out.println("Enter valid limit");
return;
}
// Logic of fibonacci series: 0 1 1 2 3 5 8 13....
// Series started with 0, 1 and after that each new terms is the sum of last two terms
printFibonacci(limit);
printFibonacci1(limit);
}
/**
* Time O(n)
* Space Input O(1)
* Space Auxiliary O(1)
* @param limit input
*/
private static void printFibonacci1(int limit) {
System.out.print("[");
if (limit == 1) {
System.out.print(0);
} else if (limit == 2) {
System.out.print(0 + " ");
System.out.print(1);
} else {
int a = 0; // First number of fibonacci
int b = 1; // Second number of fibonacci
System.out.print(0 + " ");
System.out.print(1 + " ");
int count = 3;
while (count <= limit) {
int c = a + b;
System.out.print(c + " ");
a = b;
b = c;
count++;
}
}
System.out.print("]");
}
/**
* Time O(n)
* Space Input O(1)
* Space Auxiliary O(n)
* @param limit input
*/
private static void printFibonacci(int limit) {
List<Integer> fib = new ArrayList<>();
if (limit == 1) {
fib.add(0);
} else if (limit == 2) {
fib.add(0);
fib.add(1);
} else {
int a = 0; // First number of fibonacci
int b = 1; // Second number of fibonacci
fib.add(0);
fib.add(1);
int count = 3;
while (count <= limit) {
int c = a + b;
fib.add(c);
a = b;
b = c;
count++;
}
}
System.out.println(fib);
}
}