How can I implement the modulus operator in Commodore 64 Basic? There are not a lot of math functions to work with, and modulus would be very handy.
4 Answers
For a power-of-two modulus in the range 2 to 32768, nothing will beat using the AND
operator with a value of (modulus-1). While the version of Microsoft BASIC on the Apple won't allow such usage, the one in 8-bit Commodore machines will. One could compute "Y=X mod 32" via Y = X AND 31
. While this approach only works for powers of two, it is definitely worth using for scenarios involving such values.
While I'd be inclined to put it into a DEF FN() statement, the problem is that functions only take one argument and for modulo you need two.
As others noted, you can write a subroutine for this - easy enough. However, if you want to be a bit more clever and you're not using the USR() function for anything else, you could follow the code listed on this page which described how to implement a USR() call to machine language code on a C64 and they've specifically implemented MOD with it.
The following implements Y % X, populating RE with the remainder.
Below I set up 103 % 10 on lines 10 and 20 as an example use.
10 x = 10
20 y = 103
30 gosub 1000
40 print re
50 end
1000 rem mod operation
1010 re = y - ((y/x)*x)
1020 return
-
Slow algorithm. But more importantly shouldn't 1010 reference RE instead of R? Commented Mar 27, 2019 at 4:55
-
4RE = Y - ((Y/X)*X); would be a way to get the modulo with no iterations.– PaulHKCommented Mar 27, 2019 at 5:58
-
3It would need to be Y-(INT(Y/X)*X) but that's about as good as you'll get with the built-in BASIC. There are several extensions such as Simon's BASIC that add explicit modulo functions though. Commented Mar 27, 2019 at 6:09