-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17. Print_the_fibonacci_sequence.js
More file actions
39 lines (31 loc) · 1021 Bytes
/
17. Print_the_fibonacci_sequence.js
File metadata and controls
39 lines (31 loc) · 1021 Bytes
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
//*------ Print the fabonacci sequence
//? This program prompts the user to enter the number of terms and then prints the fabonacci sequence up to that number of terms. The fabonacci series is a series of numbers where each number is the sum of the last two proceding ones, usually starting with 0 and 1.
//* method 1
let numTerms = Number(
prompt("Enter the number of terms in the Fibonacci sequence:")
);
let fibArr = [0, 1];
if (!isNaN(numTerms) && Number.isInteger(numTerms) && numTerms >= 0) {
if (numTerms === 0) {
fibArr = [0];
} else if (numTerms === 1) {
fibArr = [0, 1];
} else {
for (let i = 2; i < numTerms; i++) {
fibArr[i] = fibArr[i - 1] + fibArr[i - 2];
}
}
console.log(fibArr.join(", "));
} else {
console.log("Invalid input");
}
//* method 2
function fibonacci(n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
// Example usage:
console.log(fibonacci(6)); // 8 (the 6th number in the Fibonacci sequence is 8)