The Fibonacci numbers have many applications in computer programming. Today we're going to write a function that returns individual numbers from the Fibonacci sequence.
ASP
function fib(x)
dim fibArray()
redim fibArray(x)
fibArray(0) = 0
fibArray(1) = 1
for i = 2 to x
fibArray(i) = fibArray(i - 1) + fibArray(i - 2)
next
fib = fibArray(x)
end function
PHP
function fib($x)
{
$fibArray[0] = 0;
$fibArray[1] = 1;
for($i = 2; $i <= $x; $i++)
{
$fibArray[$i] = $fibArray[$i - 1] + $fibArray[$i - 2];
}
return $fibArray[$x];
}
So, for example, fib(8) will return 21, because the Fibonacci sequence is 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...
No comments:
Post a Comment