Sum of digits
BlitzMax Forums/BlitzMax Programming/Sum of digits
| ||
| 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 :) |
| ||
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
|
| ||
| Yep, you are right, have absolutely overlooked that. Thanks! |
| ||
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. |
| ||
| 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! |