26

I am newbie.

I want to make small app which will calculate the sum of all the digits of a number.

For example, if I have the number 2568, the app will calculate 2+5+6+8 which is equal with 21. Finally, it will calculate the sum of 21's digits and the final result will be 3 .

Please help me

Hodorogea Alexandru
  • 449
  • 2
  • 5
  • 11
  • 1
    If you treat the number as a string ('2568'), then split the string on every character (str.split('')), you will have every digit listed out separately in an array. Each digit is still a string, but you can then cast each to a number and add them up. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt – mikkelrd Jul 12 '16 at 16:45
  • How could I tell the script to take the number from a specific input instead of a given number? – Hodorogea Alexandru Jul 12 '16 at 17:03
  • https://jsfiddle.net/18hc4hgd/ my work so far – Hodorogea Alexandru Jul 12 '16 at 17:13
  • Possible duplicate of [sum of the digits of a number javascript](http://stackoverflow.com/questions/9138064/sum-of-the-digits-of-a-number-javascript) – le_m Jul 12 '16 at 18:28

8 Answers8

55

Basically you have two methods to get the sum of all parts of an integer number.

  • With numerical operations

    Take the number and build the remainder of ten and add that. Then take the integer part of the division of the number by 10. Proceed.

var value = 2568,
    sum = 0;

while (value) {
    sum += value % 10;
    value = Math.floor(value / 10);
}

console.log(sum);
  • Use string operations

    Convert the number to string, split the string and get an array with all digits and perform a reduce for every part and return the sum.

var value = 2568,
    sum = value
        .toString()
        .split('')
        .map(Number)
        .reduce(function (a, b) {
            return a + b;
        }, 0);

console.log(sum);

For returning the value, you need to addres the value property.

rezultat.value = sum;
//      ^^^^^^

function sumDigits() {
    var value = document.getElementById("thenumber").value,
        sum = 0;

  while (value) {
      sum += value % 10;
      value = Math.floor(value / 10);
  }
  
  var rezultat = document.getElementById("result");
  rezultat.value = sum;
}
<input type="text" placeholder="number" id="thenumber"/><br/><br/>
<button onclick="sumDigits()">Calculate</button><br/><br/>
<input type="text" readonly="true" placeholder="the result" id="result"/>
Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
39

How about this simple approach using modulo 9 arithmetic?

function sumDigits(n) {
  return (n - 1) % 9 + 1;
}
fethe
  • 677
  • 6
  • 12
  • Excellent example, though I personally do not fully get the idea how this works ... I mean, suppose `n = 12`, then `12-1 = 11`, `11 % 9 = 1` and `1 + 1 = 2`, yet it should be `3` ... – AlexShevyakov Jan 28 '18 at 12:46
  • 2
    Actually `11 % 9 = 2`, not 1, so `1 + 2 = 3` – fethe Jan 28 '18 at 18:43
  • 3
    note: it finds the sum of digits *recursively* (it is not clear from the title of the question and the accepted answer) – jfs Mar 27 '18 at 16:19
  • 2
    @AlexShevyakov ignore the -1 and +1, then it is just n%9. Since a number n=10^k*a_k + 10^(k-1)*a_(k-1)...10^0*a_0. Modulo 9 removes all all 10^i, since 10^i mod 9 = 1. Then the sum is created modulo 9 as well. When you imagine -1 shifts the whole number line by one to the left, you get also the nines correctly. After that you simply add 1 again. – Robert Eisele Feb 27 '19 at 10:48
  • This is elegant! I had to read about modulo 9 arithmetic to understand it. – Raknos13 May 14 '19 at 08:30
  • @FedericoAntonucci However, the function seems to fail if n % 9 = 1 – Raknos13 May 14 '19 at 08:31
  • @R3l1c not really, on which value for n you consider the function fails? For example taking 10: 10 % 9 = 1 -> (10 - 1) % 9 + 1 -> 9 % 9 + 1 -> 0 + 1 -> 1 – fethe May 14 '19 at 17:31
  • 2
    @FedericoAntonucci Apparently it fails for all numbers greater than 10 which have remainder 1 on division with 9. For eg. 19, 28, 37, 46, ... and so on. The function should return 10 for these cases but instead returns 1. – Raknos13 Jun 19 '19 at 10:27
  • 4
    @R3l1c the function should return rhe sum recursively, that's exactly what the question asks, read it again please. This solution works perfect for this question – fethe Jun 19 '19 at 14:03
  • 1
    This should be the answer. This is much faster and much more elegant – Jonas Grønbek May 25 '20 at 23:07
  • Usage of that function was a waste of time for me, because I didn`t need the recursive version of the sum. I needed a function that just give immediate (intermediate) sum of digits. And this function fails for that case as noted by @Raknos13. – Konard May 30 '20 at 11:19
  • Unfortunatelly it doesn't work all the time. – Олег Войтинський Feb 22 '21 at 17:32
  • 2
    For example sumDigits(19) returns 1 instead of 2 – Олег Войтинський Feb 22 '21 at 17:32
  • 1 is the right answer. 1 + 9 = 10 -> 1 + 0 = 1 – fethe Feb 25 '21 at 22:42
  • This returns 2 for 29 , (29-1)%9+1 = 28%9+1 = 1+ 1 =2 , but the expected result is 2+9 = 11 – ganesh Jul 17 '23 at 12:12
  • @ganesh the question was how to add recursively until getting only 1 digit, not to sum all digits. So 11 -> 1+1 = 2 Read the question again. – fethe Jul 17 '23 at 18:35
5

With mathy formula:

function sumDigits(n) { 
    return (--n % 9) + 1;
}

Without mathy formula:

function sumDigits(n) {
    if (typeof n !== 'string') {
        n = n.toString();
    }    
    if (n.length < 2) {
        return parseInt(n);
    }
​
    return sumDigits(
        n.split('')
         .reduce((acc, num) => acc += parseInt(num), 0)
    );
}
WesleyAC
  • 523
  • 6
  • 11
3

let's try recursivity

function sumDigits(n) {
  if (n < 10) return n
  return sumDigits(n % 10 + sumDigits(Math.floor(n / 10)))
}

sumDigits(2) // 2
sumDigits(2568) // 3
Envy Hion
  • 184
  • 1
  • 8
2

The sum of digits can be calculated using that function (based on other answers):

function sumDigits(n) {
    let sum = 0;
    while (n) {
        digit = n % 10;
        sum += digit;
        n = (n - digit) / 10;
    }
    return sum;
}

If you really need to sum the digits recursively there is recursive version of the function:

function sumDigitsRecursively(n) {
    let sum = sumDigits(n);
    if (sum < 10)
        return sum;
    else
        return sumDigitsRecursively(sum);
}

The sumDigitsRecursively(2568) expression will be equal to 3. Because 2+5+6+8 = 21 and 2+1 = 3.

Note that recursive solution by @FedericoAntonucci should be more efficient, but it does not give you intermediate sum of digits if you need it.

Konard
  • 2,298
  • 28
  • 21
  • The question is about recursive sum of digits – fethe May 30 '20 at 13:09
  • @FedericoAntonucci but you didn't name your function as `sumDigitsRecursively` and it did confised me, because I was looking for the method to just sumDigits. My answer contains solution that gives the same results as yours. Why did you voted my answer down? – Konard May 30 '20 at 13:26
  • cause recursive solution is no better than every other answer, and it's the less elegant solution – fethe May 30 '20 at 13:32
  • I got here when I was looking for just the sum of digits of the number, and the accepted answer do not contain a function that just receives the number and returns the sum. So I made it. Accepted solution makes a call to `Math.float`, but there is no need to do so. So for my task this is a better solution. Also the recursive version is only a bit less efficient than yours (and I wrote about it in the answer), but it is easy to understand. On the other hand you didn't explain how your solution work, and didn`t name it correctly so it caused the confusion for me and for @Raknos13. – Konard May 30 '20 at 14:12
  • I was just answering the question, it didn't ask for what you are saying, you should read the whole question, not just the title – fethe May 30 '20 at 21:33
2

You could do it this way.

function sums(input) {
    let numArr = input.toString().split('');
    let sum = numArr.reduce((a, b) => Number(a) + Number(b));
    return sum < 10 ? sum : sums(sum);
}
Valor_
  • 3,461
  • 9
  • 60
  • 109
0

Expanding upon @fethe 's answer, this sumOfDigit function is able to handle large number or BigInt

function sumOfDigits(n) { 
  return (Number.isSafeInteger(n)) ? (--n % 9) + 1 : Number((--n % 9n) + 1n);
}

console.log(sumOfDigits(101)); // 2
console.log(sumOfDigits(84932)); // 8
console.log(sumOfDigits(900000000000000000000000009n)); // 9
yogski
  • 181
  • 1
  • 10
0

you can use this function and pass your number to it:

const solution = (n) => {
    const arr = `${n}`
    let sum = 0;
    for (let index = 0; index < arr.length; index++) {
        sum += parseInt(arr[index])
    }
    return sum;
}
Dawood Valeed
  • 155
  • 1
  • 3