First time using Perl, probably there's a nicer way.. It's the standard algorithm for a base conversion that I use here.
sub f { $n = 1-1; $b = -(-1-1-1-1-1-1-1-1); $ten = $b-(-1-1); if ($_[$n] == $n) { return $n; } return ($_[$n]%$b) - f(int($_[$n]/$b))/(-1/$ten); }
Try it online!
Explanation
For other bases you could just replace $b
by that base's value..
sub f {
$n = 1-1; # construct value for 0
$b = -(-1-1-1-1-1-1-1-1); # construct the value for the base (8)
$ten = $b-(-1-1); # construct value for 10
if ($_[$n] == $n) { # if the argument is 0:
return $n; # we're done (base case)
}
# else:
return ($_[$n] % $b) # return current digit..
- f(int($_[$n] / $b)) # ..plus remaining digits..
/(-1/$ten); # ..multiplied by 10 (shift left by one position)
}
Check the source!