[math-fun] counter mod N
29 May
2014
29 May
'14
8:48 p.m.
Suppose your computer wants to count 5,4,3,2,1,0,N-1,N-2,... forever (counting down modulo N). What to do? int J,K; forever( K=K-1; J=K mod N; } forever{ K=K-1; if(K<0){ K=K+N; } } both work, but one involves slow division, other slow if statement. Actually the first one fails when K overflows. forever{ K=K-1; K = K + ((K>>31)&N) ; } (here assuming 32-bit wordsize), has neither flaw. -- Warren D. Smith http://RangeVoting.org <-- add your endorsement (by clicking "endorse" as 1st step)
4193
Age (days ago)
4193
Last active (days ago)
0 comments
1 participants
participants (1)
-
Warren D Smith