product of digit of sum
15.11.2023 1 min readAs an exercise, I’ve been trying to write code that’s more “functional”. This was a nice one to practice some recursion!
Crystal:
def sum_dig_prod(*args)
sum = args.sum
sum_arr = sum.to_s.chars.map { |i| i.to_i }
product = sum_arr.reduce { |a, b| a * b }
return product if product.to_s.size == 1
sum_dig_prod(product.to_i)
end
Nim:
func sumDigProd(args: varargs[int]): int =
let sum = args.toSeq.foldl(a + b)
let sumArr = ($sum).toSeq.mapIt(($it).parseInt)
let prod = sumArr.foldl(a * b)
if ($prod).len == 1: return prod
sumDigProd(prod)
Raku:
sub sum-dig-prod(*@args) {
my $s = [+] @args;
my @str-arr = $s.Str.comb;
my $prod = [*] @str-arr;
return $prod if $prod.Str.comb.elems == 1;
sum-dig-prod($prod);
}
Raku really shines when it comes to problems like this - prefix operators keep the code short and concise.
Javascript:
function sumDigProd(...args: number[]) {
const sum = args.reduce((acc, curr) => acc + curr);
const arr = sum
.toString()
.split("")
.map((i) => parseInt(i));
const prod = arr.reduce((acc, curr) => acc * curr);
if (prod.toString().length == 1) return prod;
return sumDigProd(prod);
}
Built with Astro and Tailwind 🚀