How can i optimise this ? Am getting timeout error when i executes this I am trying to execute this on my wampserver on a windows 10. This code is actually that i wrote for a test but the test fails if i get the values of $a and $b as huge.
Any help will be welcome. Thank you.
* @param $n
* @param false $offset
* @param false $injectResult
* @return int|mixed
*/
Seems that this part is the worm
function fibonacci($n, $offset = false, $injectResult = false)
{
if ($offset == $n && $injectResult) {
return $injectResult;
}
if ($n == 0) {
return 0;
}
if ($n == 1) {
return 1;
}
if ($n > 1) {
return fibonacci($n - 1) + fibonacci($n - 2);
}
}
/**
* Function to sum the fibonacci series result
* @param $a
* @param $b
* @return float|int
*/
This part seems ok
function sumFibonacci($a, $b)
{
$diff = $b - $a;
$result = [];
for ($i = 0; $i <= $diff; $i++) {
if ($i == 0) {
$result[$i] = fibonacci($a);
} else {
$result[$i] = fibonacci($a + $i, $a - ($i - 1), $result[$i - 1]);
}
}
return array_sum($result);
}
// Example of how to use it
echo sumFibonacci(38,58);
/**
* How can i optimise this if $a = 38 $b= 58 e.g sumFibonacci(38,58);
*/ ```
I solved it by modified the function to be non recursive
{
$numnar1 = 0;
$numnar2 = 1;
$count = 0;
$result='';
while ($count < $numnar) {
$result = $numnar1;
$numnar3 = $numnar2 + $numnar1;
$numnar1 = $numnar2;
$numnar2 = $numnar3;
$count++;
}
return $result;
}
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.