Sum of digits

BlitzMax Forums/BlitzMax Programming/Sum of digits

jsp(Posted 2009) [#1]
I am looking for a very fast function to calculate the sum of digits of a long variable.

Using now a simple loop:
Function QSum2:int(Lo:Long)  
 Local QS:int
 For Local i:Int = 0 To String(Lo).length - 1
  Qs:+Int(String(Lo)[i..i+1])
 Next 
 Return Qs
End Function


But it is definately too slow. Any other ideas are welcome :)


tonyg(Posted 2009) [#2]
It should be much quicker if you convert your long into a string in one hit rather than keep casting it....
Function tg_qsum2:Int(lo:Long)
  Local QS:Int
  Local instring:String=String(lo)
  Local stringlen:Int=instring.length-1
  For Local i:Int = 0 To stringlen
     Qs:+Int(instring[i..i+1])
  Next 
  Return Qs
End Function



jsp(Posted 2009) [#3]
Yep, you are right, have absolutely overlooked that.
Thanks!


PGF(Posted 2009) [#4]
This is about 10 times faster than the original:

Function QSum3:Int(num:Long)
	Local sum:Int = 0
	While num > 0
		sum :+ num Mod 10
		num = num / 10
	Wend
	
	Return sum
End Function


Could be sped up a bit but if you want the ultimate you would be better of with a bit of ASM.


jsp(Posted 2009) [#5]
Found this just as C function, but wasn't sure if it's faster by using a divide operation in the loop. But it is faster!