How to check if number is divisible by a certain number?

coder_For_Life22 picture coder_For_Life22 · Nov 24, 2011 · Viewed 150.6k times · Source

I am using AndEngine to add sprites to the screen and come across using the movemodifier method.

I have two integers MaxDuration and MinDuration;

What i want to do is when the user gets to a score of a certain increment.

Like for example.. when the user gets to 20(the integer changes) when the user gets to 40(the integer changes). So basically count by 20 and every time the score meets a number divisible by 20 the integer's change. I hope this makes sense.

Is there any method or way to do this? I have an UpdateTime handler that can check the score just about every second.

Any ideas?

Answer

Cristian picture Cristian · Nov 24, 2011
n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;