Computer >> Computer tutorials >  >> Programming >> Javascript

Adding digits of a number using more than 2 methods JavaScript


We are required to write a JavaScript function that in a number and repeatedly sums its digit until it converses to a single digit number.

We will solve this problem by two methods −

Method 1: Using loops

This solution makes use of the while loops to recursively add up the digits of the number.

Example

const num = 123456;
const addDigits = (num = 1) => {
   let sum = num;
   while(sum % 10 !== sum){
      let sum1 = 0;
      while(sum > 0){
         sum1 += sum % 10;
         sum = Math.floor(sum / 10);
      }
      sum = sum1;
   };
   return sum;
};
console.log(addDigits(num));

Method 2: Using a constant time solution (O(1) time complexity)

This solution makes use of the Congruence formula of Mathematics, and readers are advised to explore this formula for a better understanding of this solution.

Example

const num = 123456;
const addDigits = (num = 1) => {
   let predicate = (num - 1) % 9;
   return ++predicate;
};
console.log(addDigits(num));

Output

And the output in the console for both methods will be −

3