Created
March 5, 2013 14:21
-
-
Save gwainor/5090612 to your computer and use it in GitHub Desktop.
This little program prints out 500 of the fibonacci numbers. You can increase of decrease the result number by changing `$reach` variable. This program does not adds "E+15" thing to numbers or so. It gives exact result.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Function - addNumbers() | |
* | |
* This function adds the numbers old school way. It starts from last digit | |
* and add them by one by one. If results greater than 9, it takes the first | |
* digit to add it to next adding step. | |
* | |
* @author Gökhan ÖZTÜRK <[email protected]> | |
* @param int | |
* @param int | |
* @return string Since some numbers could be greater than max number limit, | |
* it returns result as string. | |
*/ | |
function addNumbers($numberOne, $numberTwo) | |
{ | |
// if number one is smaller than the number two, we are adding | |
// "0" as the first number of number one. This will not affect the adding | |
// But with this we will have same count of arrays. | |
if (strlen($numberOne) != strlen($numberTwo)) { | |
$numberOne = 0 . $numberOne; | |
} | |
// We are splitting the numbers. We will add the nummbers one by one | |
$numberOne = str_split($numberOne); | |
$numberTwo = str_split($numberTwo); | |
$result = $remaining = ""; | |
for ($i = count($numberOne) - 1; $i >= 0 ; $i--) { | |
// We are adding number one to numbertwo (last numbers) | |
$r = $numberOne[$i] + $numberTwo[$i]; | |
// If there is any remaining from past adding in the loop | |
// add them | |
if ($remaining != "") { | |
$r = $r + $remaining; | |
} | |
// If adding results with a two digit, we will take only last digit | |
// and the other digit will be remaining and will be added to next adding | |
if ( (strlen($r) == 2) and ($i !== 0) ) { | |
$temp = str_split($r); | |
$remaining = $temp[0]; | |
$r = $temp[1]; | |
} else { // There is no remaining so empty the variable so it won't mixed up. | |
$remaining = ""; | |
} | |
// Add the result to the begining of the result. | |
$result = $r . $result; | |
} | |
return $result; | |
} | |
// The fibonacci starts with 1 + 1. So we are defining them at first | |
$numberOne = 1; | |
$numberTwo = 1; | |
$reach = 500; // how many times? | |
// We are adding first two digits to the result array | |
$result = array($numberOne, $numberTwo); | |
for ($i=2; $i < $reach; $i++) { | |
$r = addNumbers($numberOne, $numberTwo); | |
$numberOne = $numberTwo; | |
$result[] = $numberTwo = $r; | |
} | |
// Printing out the result! | |
foreach ($result as $res) { | |
echo $res . "<br>\r\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment