Whats the best algorithm to find digit sum on as3? For example to convert 1999 = 1+9+9+9 = 28 = 2+8 = 10 = 1+0 = 1. I found this on the net, but its for double-digit numbers.
function sumDigits(number) {
var remainder = number % 10;
var sum = remainder;
if(number >= 10) {
var rest = Math.floor(number / 10);
sum += sumDigits(rest);
}
return sum;}
It's as easy as getting the remainder from division by 9, and taking the result of 0 as 9.
function sumDigits(num:int):int {
if (num==0) return 0;
var red:int=num % 9;
if (red==0) return 9; else return red;
}
The logic behind this answer is simple maths. Whenever you count a sum of digits, you are receiving the value that has the same remainder from division by 9 as the original number. And since you are trying to reduce the sum to a single digit, you can only receive 0-9 as an answer, and only zero has the sum of 0, thus your function should return a number from 1 to 9. These numbers have unique values modulo 9, thus you can get the modulo 9 of original number and derive the result from that.