find the nth lucas number in javascript

To find the nth Lucas number in JavaScript, you can use a recursive function that calculates the previous two Lucas numbers until you reach the desired nth value.

index.tsx
function nthLucasNumber(n) {
  if (n === 0) return 2;
  if (n === 1) return 1;

  return nthLucasNumber(n - 1) + nthLucasNumber(n - 2);
}
138 chars
7 lines

This function checks if we want to find the 0th or 1st Lucas number, which are already defined as 2 and 1 respectively. If we want to find any other nth Lucas number, we recursively call the function with n - 1 and n - 2 until we reach the base case of n equals 0 or 1.

To use this function, simply call nthLucasNumber(n) with the desired value of n. For example, to find the 5th Lucas number:

index.tsx
nthLucasNumber(5); // returns 11
33 chars
2 lines

gistlibby LogSnag