-4

The fallowing function does not return a value when called for some reason.

function modrecursive(int $a, int $d) {
    $r = $a;
    
    if ( $d < 1) {
        throw new InvaludArgumentException('divsionAlg requires divisor be positive. Input was: ' . $d);
    }

    if ($r < 0) {
        $r = $r + $d;
        //print( "R: " .  $r . "\n"); //debug code
    }
    if ($d <= $r) {
        $r = $r - $d;
        //print( "R: " .  $r . "\n"); //debug code
    }
    
    if ($d > $r && $r >= 0) {
        print("recursive: " . $r . "\n");
        return $r;
    }
    else {
        modrecursive($r,$d);
    }
}

I have tested this multiple times, even if the if statement evaluates to true it still doesn't return a value.

Jacob
  • 7
  • 4
  • If it doesn't evaluate to true on the **first** call to it, then it hits the `else` branch, calls itself recursively and **doesn't return the result of the recursion**. You just forgot the `return` statement before `modrecursive($r,$d);` – Quentin Mar 28 '21 at 00:44
  • as stated I tested the code multiple times, that's what the 3 print statements in the code are for. – Jacob Mar 28 '21 at 00:45

1 Answers1

0

the solution for your Problem is pretty simple.

You just need to add a "return"-Statement to your "modrecursive" function call, inside your "else".

As soon as you get into your "else" nothing gets returned.

So on the end your Code should look like this:

function modrecursive(int $a, int $d) {
    $r = $a;
    
    if ( $d < 1) {
        throw new InvaludArgumentException('divsionAlg requires divisor be positive. Input was: ' . $d);
    }

    if ($r < 0) {
        $r = $r + $d;
        //print( "R: " .  $r . "\n"); //debug code
    }
    if ($d <= $r) {
        $r = $r - $d;
        //print( "R: " .  $r . "\n"); //debug code
    }
    
    if ($d > $r && $r >= 0) {
        print("recursive: " . $r . "\n");
        return $r;
    }
    else {
        return modrecursive($r,$d);
    }
}
Yannick
  • 177
  • 2
  • 13