HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Is this Fibonacci function right?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisfunctionfibonacciright

Problem

Is this a correct method of Fibonacci with recursion?

function fibb($limit,$first_numer=0,$second_number=1){
        echo $first_numer."\n";
        echo $second_number."\n";
        if($limit > 0){
            fibb($limit-2,$first_numer+$second_number,($first_numer+$second_number+$second_number));
        }
}

Solution

In a sense, your function does produce the right numbers. However, the termination condition is not quite right. For example, fibb(3) and fibb(4) produce identical output: each prints six numbers. Why six? The most natural interpretation of the parameters would be that $limit should specify the number of items in the sequence to be printed.

The root of the problem is that each call to fibb() prints two lines, which means that output will always be printed in pairs. Normally, you would want to print just one number per call.

In addition, your naming is unconventional. Why fibb() with two bs? Also, $first_numer is misspelled.

function fibonacci($limit, $first_number=0, $second_number=1) {
    if ($limit <= 0) {
        return;
    }
    echo "$first_number\n";
    fibonacci($limit - 1, $second_number, $first_number + $second_number);
}

Code Snippets

function fibonacci($limit, $first_number=0, $second_number=1) {
    if ($limit <= 0) {
        return;
    }
    echo "$first_number\n";
    fibonacci($limit - 1, $second_number, $first_number + $second_number);
}

Context

StackExchange Code Review Q#40426, answer score: 4

Revisions (0)

No revisions yet.