Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate alternating sum of digits of an integer in Perl 6?

Tags:

raku

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?

like image 925
Eugene Barsky Avatar asked Dec 08 '17 19:12

Eugene Barsky


People also ask

How do you find the sum of the digits of a number?

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.


1 Answers

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:<-> ... *)
like image 124
moritz Avatar answered Sep 18 '22 17:09

moritz