What in layman's terms is a Recursive Function using PHP

前端 未结 16 1127
庸人自扰
庸人自扰 2020-11-22 05:50

Can anyone please explain a recursive function to me in PHP (without using Fibonacci) in layman language and using examples? i was looking at an example but the Fibonacci to

16条回答
  •  一向
    一向 (楼主)
    2020-11-22 06:41

    Recursion used for Kaprekar's constant

    function KaprekarsConstant($num, $count = 1) {
        $input = str_split($num);
        sort($input);
    
        $ascendingInput  = implode($input);
        $descendingInput = implode(array_reverse($input));
    
        $result = $ascendingInput > $descendingInput 
            ? $ascendingInput - $descendingInput 
            : $descendingInput - $ascendingInput;
    
        if ($result != 6174) {
            return KaprekarsConstant(sprintf('%04d', $result), $count + 1);
        }
    
        return $count;
    

    }

    The function keeps calling itself with the result of the calculation until it reaches Kaprekars constant, at which it will return the amount of times the calculations was made.

    /edit For anyone that doesn't know Kaprekars Constant, it needs an input of 4 digits with at least two distinct digits.

提交回复
热议问题