Created
May 18, 2018 12:14
-
-
Save finagin/b5caed18b6b8f5cf3b46f46ac4e33ced to your computer and use it in GitHub Desktop.
Sum digits of number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function f($number, $recursive = false, $dec = 10) | |
{ | |
if (!is_int($dec)) { | |
throw new \Exception('dec must integer'); | |
} elseif ($dec < 2) { | |
throw new \Exception('dec must be >= 2'); | |
} | |
$sum = 0; | |
do { | |
$sum += $number % $dec; | |
$number = $number / $dec; | |
} while (abs($number) > 0); | |
$self = __METHOD__; | |
return $recursive && abs($sum) > $dec ? $self($sum, $recursive) : abs($sum); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment