4

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.

13

Using this expression

A-INT(A/B)*B

enter image description here

4

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.

2

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.

0

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
  • Slow algorithm. But more importantly shouldn't 1010 reference RE instead of R? – manassehkatz Mar 27 at 4:55
  • 3
    RE = Y - ((Y/X)*X); would be a way to get the modulo with no iterations. – PaulHK Mar 27 at 5:58
  • 2
    It 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. – Matthew Barber Mar 27 at 6:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.