"In all my years of computer programming, I have accepted that modular arithmetic works differently with negative numbers than positive numbers. For example, 13 mod 4 equals 1, and 9 mod 4 equals 1 as well, and 5 mod 4 equals 1 also, and obviously 1 mod 4 equals 1. But then −3 mod 4 equals −3, not 1, even though −3 is a number of the form 4 k + 1?"
"That's the answer you get with seemingly every general purpose programming language you can use today. It was the case with QBasic (take my word for it), it is the case with JavaScript and it is the case with Java, Scala and Kotlin (though there's a caveat I'll give at the end). If you're reading this on a Web browser on a laptop or desktop computer, you can easily verify how JavaScript deals with negative numbers and modular arithmetic."
Modular arithmetic behaves differently for negative numbers in many programming languages. Positive examples: 13 mod 4 = 1; 9 mod 4 = 1; 5 mod 4 = 1; 1 mod 4 = 1. Negative example: −3 mod 4 yields −3, not 1, despite −3 fitting 4k+1. Many general-purpose languages (QBasic, JavaScript, Java, Scala, Kotlin) implement the % operator to return negative remainders for negative operands. A web browser console can be used to verify JavaScript behavior directly. Scala's online REPL shows that (-47 to 49 by 4).map(_ % 4) produces −3 several times followed by 1 several times.
Read at Medium
Unable to calculate read time
Collection
[
|
...
]