Showing posts with label perl. Show all posts
Showing posts with label perl. Show all posts

Wednesday, 28 March 2018

Sum of digits function in Excel and perl. sd(n)

In Excel

From : http://www.listendata.com/2013/02/excel-sum-of-digits-in-number-using-non.html

01. Formula - Sum & Index

Assuming a value is entered in cell B4 i.e. 45454. The sum of the digits of this number is 22.

=SUM(INDEX(1*(MID(B4,ROW(INDIRECT("1:"&LEN(B4))),1)),,))

02. Formula - Sumproduct & Indirect


Assuming a value is entered in cell B4 i.e. 45454. The sum of the digits of this number is 22.

=SUMPRODUCT(MID(B4,ROW(INDIRECT("1:" & LEN(B4))),1)*1)

03. Formula - Sumproduct & Indirect


Assuming a value is entered in cell B4 i.e. 45454. The sum of the digits of this number is 22.

=SUMPRODUCT(MID(B4,ROW(OFFSET($A$1,,,LEN(B4))),1)+0)

04. Formula - Array Formula


For the people who enjoys hitting Ctrl Shift Enter. Assuming a value is entered in cell B4 i.e. 45454. The sum of the digits of this number is 22.

=SUM(MID(B4,ROW(INDIRECT("1:" & LEN(B4))),1)*1)

Note : Press F2 and Hit Ctrl Shift Enter to confirm the above array formula.

In Perl 

sub sd() {
#sum of digits
local $t =0;
        map { $t+= $_; } split //,$_[0];
        return $t;
}

This subroutine splits the first argument $_[0]  into a digits array then adds the elements of the array by maping over the elements.   1234 => 1,2,3,4 => 1+2+3+4 => 10.