VOOZH about

URL: https://www.geeksforgeeks.org/javascript/javascript-program-for-lucas-numbers/

⇱ JavaScript Program for Lucas Numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

JavaScript Program for Lucas Numbers

Last Updated : 3 May, 2024

Lucas numbers are similar to Fibonacci numbers. Lucas numbers are also defined as the sum of its two immediately previous terms. But here the first two terms are 2 and 1 whereas in Fibonacci numbers the first two terms are 0 and 1 respectively. 
Mathematically, Lucas Numbers may be defined as:
👁 {\displaystyle L_{n}:={\begin{cases}2&{\text{if }}n=0;\\1&{\text{if }}n=1;\\L_{n-1}+L_{n-2}&{\text{if }}n>1.\\\end{cases}}}

The Lucas numbers are in the following integer sequence:
2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123 …………..

Write a function int lucas(int n) n as an argument and return the nth Lucas number.

Examples:

Input : 3
Output : 4

Input : 7
Output : 29

Recursive Approach

Implement a recursive function that generates Lucas numbers based on the definition. The function should terminate when reaching the desired index in the sequence.

  • Use a recursive function to compute the Lucas number based on the given definition.
  • Base cases: L(0)=2 and ?(1)=1.
  • Recursively compute L(n) as ?(?−1)+?(?−2) for ?>1.

Example: Implementation to generate lucas number using recursive approach.


Output
123

Time Complexity The time complexity is ?(2^?) due to the exponential growth of function calls.

Space Complexity The space complexity is ?(?) due to the recursive function calls occupying stack space.

Iterative Approach

Implement an iterative function that generates Lucas numbers iteratively. Iterate from the starting index to the desired index in the sequence, calculating each Lucas number based on the previous two numbers.

Example: Implementation to generate lucas number using iterative approach.


Output
76

Time Complexity The time complexity is ?(?) as we iterate through the loop ? times to calculate the ?-th Lucas number.

Space Complexity The space complexity is ?(1) as we use only a constant amount of extra space for variables.

Comment