Created
January 6, 2020 04:40
-
-
Save Francis-Njoku/7d2ed99f6390772d5f567ff8ef3b3d4c to your computer and use it in GitHub Desktop.
Fibonacci sequence with index of first term to contain 1000 digits
This file contains 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 to generate fibonacci sequence that contains large numbers | |
function getFibonacci() { | |
$i = '0'; | |
$k = '1'; //first fibonacci value | |
yield $k; | |
while(true) { | |
// gmp_add to add two gmp number (www.php.net/manual/en/ref.gmp.php) | |
$k = gmp_add($i, $k); | |
// gmp_subtract to subtract $i from $k | |
$i = gmp_sub($k, $i); | |
yield $k; | |
} | |
} | |
/* | |
* This function finds and print the first fibonacci sequence number | |
* with 1000 digits | |
*/ | |
function getFab1() | |
{ | |
// fibonacci series from $this->getFibonacci2() | |
foreach($this->getFibonacci() as $value) { | |
// Function breaks with the first 1000 digits | |
if (strlen($value) == 1000) { | |
break; | |
} | |
} | |
// prints the value | |
echo $value, PHP_EOL; | |
} | |
/* | |
* This function prints fibonacci sequence starting from | |
* digits 1000 $n number of times | |
*/ | |
function Fibonacci($n) | |
{ | |
//$ti = $n + $this->getFabCounter(); | |
// Initialize first and second number to 0 and 1 | |
$num1 = 0; | |
$num2 = 1; | |
// initialize counter and set to 0 | |
$counter = 0; | |
// send the flow to iterative while loo[ where we get the next number | |
// that starts with 1000 digits and adding the previous two number | |
// and simultaneously we swap the first number with the second, and second | |
// with third | |
while ((strlen($num1) >= strlen($this->getFab1())) && ($counter < $n)){ | |
echo ' '.$num1; | |
$num3 = $num2 + $num1; | |
$num1 = $num2; | |
$num2 = $num3; | |
$counter = $counter + 1; | |
} | |
} | |
/* | |
* This sets and runs fibonacci sequence with index of the first term to contain 1000 digits | |
*/ | |
$n = 10; | |
$this->Fibonacci($n); | |
?> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment