A number is divisible by 11 if its alternating sum of digits is divisible by 11.
So, e.g. if number is 1595
, +1 -5 +9 -5 == 0
, so 1595 is divisible by 11. How to implement such a sum? Here is my solution, but it's too complex and works only if the number of digits is even.
my $number = 1595;
say [+] $number.comb.map({$^a - $^b});
What's the best way to do it?
We can calculate the sum of digits of a number by adding a number's digits while ignoring the place values. So, if we have the number 567, we can calculate the digit sum as 5 + 6 + 7, which equals 18.
say [+] 1595.comb Z* (1, -1, 1 ... *)
To break it down: .comb returns a list of characters, and Z* multiplies that list element-wise with the sequence on the RHS.
This sequence is a geometric sequence, which the ...
series operator can deduce from the three elements. Since the zip operator Z
stops at the shortest sequence, we don't have to take care to terminate the sequence on the RHS.
Another way to write the same thing is:
say [+] 1595.comb Z* (1, -* ... *)
Where -*
is the explicit negation of the previous value, applied to the initial element to generate the next one.
You could also write that as
say [+] 1595.comb Z* (1, &prefix:<-> ... *)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With