4 ms·
If n < 0 record sign and invert. (If we can't use unary "-" then just use two blocks of code). Set dividend to 0. Loop against n, incrementing loop index by 3.
by Tloewald 14y ago
If n < 0 record sign and invert. (If we can't use unary "-" then just use two blocks of code).
Set dividend to 0.
Loop against n, incrementing loop index by 3.
Increment dividend by 1 per loop iteration.
Invert dividend if we inverted n.
Dividend is your answer (or add the remainder to a more precise floating point result).
No bit twiddling. Small RAM footprint. Obviously correct. (This is really just an unoptimized version of the "clever" solution.)
For Oracle though -- create a database of numbers and their thirds and then lookup the answer.
- ColinWright 14y agoHow do you increment without using "+"?
- sunir 14y agoIncrement operator ++
- ciupicri 14y agoThen as one of the comments says why not use the /= operator directly?
- femto 14y agoInvert all the least significant bits, up to and including the least significant zero.
- Tloewald 14y agoNice suggestion if we disallow ++ and still simpler than most of the other proposed solutions.
- podperson 14y ago++ Or += which is needed for the bitshift solution.