Skip to content

Instantly share code, notes, and snippets.

@joshuamorse
Created April 10, 2011 20:57
Show Gist options
  • Save joshuamorse/912716 to your computer and use it in GitHub Desktop.
Save joshuamorse/912716 to your computer and use it in GitHub Desktop.
Returns the result of a supplied position in the Fibonacci Sequence
<?php
/**
* Returns the result of a supplied position in the Fibonacci Sequence.
*
* @param mixed $n
* @access public
* @return integer
*/
function get_fibonacci_position($n)
{
if (!is_int($n))
{
throw new Exception($n . ' is not a number!');
}
// Starting the array on key 1 for semantic meaning (e.g. 1 = 1st)
// Per Fibonacci spec, the 0 and 1 are given values.
$result = array(
1 => array(
'last' => null,
'previous' => null,
'current' => 0,
),
2 => array(
'last' => null,
'previous' => 0,
'current' => 1,
),
);
/**
* Since we've already defined the first two numbers in the sequence,
* we only need to iterate from next entry.
*/
$init_iterator = (count($result) + 1);
for ($i = $init_iterator; $i < ($n + 1); ++$i)
{
$r =& $result;
$r[$i]['last'] = $result[($i - 2)]['current'];
$r[$i]['previous'] = $result[($i - 1)]['current'];
$r[$i]['current'] = ($result[$i]['last'] + $result[$i]['previous']);
}
return $result[$n]['current'];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment