Search code examples
phprecursion

Recursive Addition PHP


I am asked to make a recursive addition of a passes value for example if the value passes is 1024 i should get the answer 7

I am using this code

function recursiveAdd($arg)
{
    $ans = floor($arg);
    if ($arg<=1) return $ans;
    if (($arg/10)>0) return $ans + floor(recursiveAdd($arg/10));
    //else return $arg % 10;
}

echo recursiveAdd(1024);

I think i am there, if i run it i get 1137 in this case the last number is what i need.

Can you please check it as i think i am not seeing the wrong recursion!

Regards


Solution

  • This one does what is requested and is a bit simplified:

    <?php
    function recursiveAdd($arg)
    {
        if ($arg>9) {
            return $arg%10 + recursiveAdd(floor($arg/10));
        } else {
            return $arg;
        }
    }
    
    echo recursiveAdd(1024);
    

    However you don't have to use recursion, things are faster and less resource hungry without:

    <?php
    function sequentialAdd($arg)
    {
        $sum = 0;
        $string = (string) $arg;
        foreach (str_split($string) as $digit) {
            $sum += $digit;
        }
        return $sum;
    }
    
    echo sequentialAdd(1024);