Calculation of cross-sums using only while loop, multiply, divide, add, subtract

What is the algorithm for calculating the cross-sum (516 = 5 + 1 + 6 = 12) with just a while loop, adding, subtracting, division and mulitply? I would use modolus, but I do not know how to replicate it only with the basic mathematical terms that I spoke about.

+4
source share
2 answers

Suppose by division you mean float-division; otherwise, you could write your own mod operation using gender separation.

O(n) time, O(1) ( n - ).

JavaScript:

function crossSum(num){
  // Find the largest power of ten and number of digits, O(n)
  var power = 1,
      numDigits = 1;
      
  while (power * 10 <= num){
    power = power * 10;
    numDigits++;
  }
  
  // Calculate cross sum, O(constant * n) = O(n)
  var sum = 0,
      digit;
  
  while (num > 0){
    digit = 0;
    
    while ((digit + 1) * power <= num)
      digit++;
      
    console.log(digit)
    sum = sum + digit;
    num = num - power * digit;
    power = power / 10;
  }
  
  return sum;
}

console.log(crossSum(516));
Hide result
+1

enter image description here

, , modulo, , - , , , . StackOverflow , , , , . , , .

-1

Source: https://habr.com/ru/post/1671911/


All Articles