find the nth lucas number in php

One way to find the nth Lucas number in PHP is by using recursion or dynamic programming. Here's an implementation using recursion:

main.php
function lucas($n) {
  if ($n == 0) {
    return 2;
  } elseif ($n == 1) {
    return 1;
  } else {
    return lucas($n - 1) + lucas($n - 2);
  }
}
148 chars
10 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.php
$n = 10;
echo "The $n-th Lucas number is: " . lucas($n);
57 chars
3 lines

Output:

main.php
The 10-th Lucas number is: 123
31 chars
2 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