How to check if my integer can be divided by 3 as below:
for(int i=0; i<24; i++){
//here, how to check if \"i\" can be divided by 3 completely(e.g. 3,
If you are using a loop, you can use the fact that every third number can be divided by 3.
for(int i = 0; i < 24; i += 3) {
System.out.println(i + " can be divided by 3");
System.out.println((i+1) + " cannot be divided by 3");
System.out.println((i+2) + " cannnot be divided by 3");
}
This avoids the need for a modulo and cuts the number of loops by a factor of 3.
Use the modulo operator.
if(i % 3 == 0)
Also see Modulo operation at Wikipedia
Check the remainder of i devided by 3
if (i % 3 == 0) {}
Use the MOD operator
for(int i=0; i<24; i++){
if( i%3 == 0 )
// It is divisible by 3
}
if( i % 3 == 0 )
The % operator delivers you the rest of the division i / 3
Well, what you could do (it might be a bit faster; it is faster on my machine) is:
boolean canBeDevidedBy3 = ((int) (i * 0x55555556L >> 30) & 3) == 0;
instead of
boolean canBeDevidedBy3 = (i % 3) == 0;
However, the multiplication trick only works for -2 <= i <= 1610612735
. This answer was inspired by this optimization question. But if I can give you a tip: use (i % 3) == 0
. It's so much simpler, and will always work.