Return to Snippet

Revision: 62924
at March 23, 2013 21:50 by Salamandern


Initial Code
function summate(n){

	var chars = new Array();
	var c;
	var l = "" + n + "";
	var ans = 0;
	l = l.length;
	
	for(var i = 0;i < l;i++){
	
		c = n;
		for(var j = 0;j<i;j++){
		
		c -= chars[j]*Math.pow(10,(l-1)-j);
		}
		
		c /= Math.pow(10,(l-1)-i);
		c = Math.floor(c);
		chars.push(c);
	}
	while(l>0){
		
		ans += chars[l-1];
		l--;
	}
	return ans;
}

Initial URL


Initial Description
This function will return the sum of the characters making up a number. For example, summate(321) will return 6. summate(123) will also return 6, because both 123 and 321 are made out of the same characters. Supports integers of any length, but only positive ones. Negatives get weird. Non-integers get rounded.

Initial Title
Summate() - Add the characters of a number

Initial Tags
math

Initial Language
JavaScript