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.
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.
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.
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 1000 REM MOD OPERATION 1010 RE = Y - ((Y/X)*X) 1020 RETURN