Skip to content

Instantly share code, notes, and snippets.

@finagin
Created May 18, 2018 12:14
Show Gist options
  • Save finagin/b5caed18b6b8f5cf3b46f46ac4e33ced to your computer and use it in GitHub Desktop.
Save finagin/b5caed18b6b8f5cf3b46f46ac4e33ced to your computer and use it in GitHub Desktop.
Sum digits of number
<?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