![]() |
VOOZH | about |
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
Table of Content
Implement a recursive function that generates Lucas numbers based on the definition. The function should terminate when reaching the desired index in the sequence.
Example: Implementation to generate lucas number using recursive approach.
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.
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.
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.