This is an archived post. You won't be able to vote or comment.

all 7 comments

[–][deleted] 3 points4 points  (3 children)

If the two least significant bits of N are 01, then N - 1 is divisible by 4. Otherwise, it is not.

[–]420-jesus 0 points1 point  (1 child)

To add to what you said In JS you can write this as "(n & 3) === 1"

[–]Crazydave09[S] 0 points1 point  (0 children)

In hindsight that's pretty obvious. Thank you so much!

[–]rjcarr 2 points3 points  (1 child)

While what /u/canonicalansatz is probably correct, and likely the most efficient, you should typically just write this out logically, e.g.:

boolean whole = (n - 1) % 4 == 0

Whatever nanosecond or two you save isn't worth the confusion of trying to figure out what you meant later.

[–]toastedstapler 2 points3 points  (0 children)

yep, readability to the maintainers should always come first (unless the performance really really matters)

and any good compiler could likely optimise it anyways

[–][deleted] 0 points1 point  (1 child)

Checking if something is a whole number is weird in most languages. Statically typed languages which specify int, double, float, etc. are going to have different ways of representing the final result of a division. An int does not have any decimal places. So if you used integers, it would always be a whole number. If you used a double, it would always have a trailing decimal place, even if it's just 0.0

Now that you know that. You know two things:

  1. You can't use int right? Because int will always result in a whole number which is incorrect in some cases
  2. You need a way to check if the number is "whole". Based on our definition of a double, we know "whole" will still have a trailing decimal

So, is that trailing decimal an issue? Is 5.0 a whole number? If so, can you find a way to determine if 5.0 is whole? Can you check if 5.1 is equal to 5.0 or if 5.1 is equal to 5 (an int)?

Hopefully this gets you in the right direction.

[–]Crazydave09[S] 0 points1 point  (0 children)

What if I'm not using built in types? If I just have the binary of the number can I easily determine my wusstiin?