27

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, 6, 15)?

}
Leem
  • 17,220
  • 36
  • 109
  • 159
  • 4
    You have about 20 questions without an accepted answer. Perhaps you could ask clearer questions or follow up on answers so they can be accepted. – Peter Lawrey Jul 11 '11 at 08:12
  • This question seems pretty clear to me. It's asking how to divide the current number in the loop by 3 and got no remainder. – Rich Feb 16 '23 at 17:24

8 Answers8

77

Use the modulo operator.

if(i % 3 == 0)

Also see Modulo operation at Wikipedia

Sebastian Wramba
  • 10,087
  • 8
  • 41
  • 58
10

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
6

Use the MOD operator

for(int i=0; i<24;  i++){
   if( i%3 == 0 )
       // It is divisible by 3

}
Talha Ahmed Khan
  • 15,043
  • 10
  • 42
  • 49
5

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.

Community
  • 1
  • 1
Thomas Mueller
  • 48,905
  • 14
  • 116
  • 132
4

Check the remainder of i devided by 3

if (i % 3 == 0) {}
Dimitar Petrov
  • 667
  • 1
  • 5
  • 16
1

inside the loop:

if (i%3 == 0)
    // it can be divided by 3

% is called "mod" or "modulus" and gives you the remainder when dividing two numbers.

These are all true:

6 % 3 == 0
7 % 3 == 1
7 % 4 == 3
BudgieInWA
  • 2,184
  • 1
  • 17
  • 31
0
if( i % 3 == 0 )

The % operator delivers you the rest of the division i / 3

Tim Meyer
  • 12,210
  • 8
  • 64
  • 97
0
if( i % 3 == 0 ){
System.out.println("can be divided by 3");
}else{
System.out.println("cant divide by 3");
}

Is this question for real?

Benny Tjia
  • 4,853
  • 10
  • 39
  • 48