Suppose we have the following problem −
There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 or 2 stairs at a time. We are required to count the number of ways, the person can reach the top.
We are required to write a JavaScript function that takes in a number n that denotes the number of stairs. The function should count and return the number of ways in which the stairs can be climbed.
Example
Following is the code −
const recursiveStaircase = (num = 10) => {
if (num <= 0) {
return 0;
}
const steps = [1, 2];
if (num <= 2) {
return steps[num - 1];
}
for (let currentStep = 3; currentStep <= num; currentStep += 1) {
[steps[0], steps[1]] = [steps[1], steps[0] + steps[1]];
}
return steps[1];
};
console.log(recursiveStaircase());
console.log(recursiveStaircase(4));
console.log(recursiveStaircase(13));Output
Following is the output on console −
89 5 377