One way to find the nth Lucas number in PHP is by using recursion or dynamic programming. Here's an implementation using recursion:
main.php148 chars10 lines
The lucas
function takes an integer parameter $n
and returns the nth Lucas number. If $n
is 0, it returns 2. If $n
is 1, it returns 1. Otherwise, it recursively computes the sum of the (n-1)th and (n-2)th Lucas numbers.
Here's how you can use the lucas
function to find the 10th Lucas number:
main.php57 chars3 lines
Output:
main.php31 chars2 lines
Note that for large values of $n
, the recursion approach may be slow and may consume a lot of memory. In such cases, it's better to use dynamic programming or memoization to avoid recomputing the same values multiple times.
gistlibby LogSnag