Finding the nth element of the lucas number sequence in JavaScript


Lucas Numbers

Lucas numbers are numbers in a sequence defined like this −

L(0) = 2
L(1) = 1
L(n) = L(n-1) + L(n-2)

Problem

We are required to write a JavaScript function that takes in a number n and return the nth lucas number.

Example

Following is the code −

 Live Demo

const num = 21;
const lucas = (num = 1) => {
   if (num === 0)
      return 2;
   if (num === 1)
      return 1;
   return lucas(num - 1) +
      lucas(num - 2);
};
console.log(lucas(num));

Output

Following is the console output −

24476

Updated on: 17-Apr-2021

149 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements