3 ms·
Yep. I remember that for my first C assignment in college we had to write a calendar, and leap year calculations needed modulos. I remember distinctly that I to
by ollien 5y ago
Yep. I remember that for my first C assignment in college we had to write a calendar, and leap year calculations needed modulos. I remember distinctly that I tore my hair out trying to figure this out, especially because I was prototyping my math in Python. I eventually resolved that I needed to constantly ensure my sum was > 0 (by adding my modulo base).
- Normal_gaussian 5y agoThat will only work for cases where a >= -b. For the more general case: > a mod b = ((a % b) + b) % b The first remainder bounds it to -b < x < b. Then adding b goes to 0 < x < 2b. Then the second remainder gets th desired 0 <= x < b. This will not work for b > max_int / 2 (solution in that case is much mkre language dependent)
- yaur 5y agoWhat's the case where the C % operator behaves in an unexpected way? I've been wiring software for about 20 years and can count zero hands the number of times someone I've worked with has had to worry about how the modulo operator behaves with negative numbers.
- housecarpenter 5y agoAn example would be if you want to find the month corresponding to a timestamp. The obvious thing to do is to scale the timestamp so that it gives you the number of months after the epoch, take that number % 12, and map 0 to January, 1 to February, etc. (assuming the epoch is in January). But if you try to do that with a timestamp from before the epoch, you'll end up with 0 for January, -11 for February, -10 for March, etc.
- yaur 5y agoNo. If your software has to deal with dates from before 1970 "seconds since the epoch" is not a reasonable choice for a time unit.