简体   繁体   中英

How to check if an integer can be divided by 3

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)?

}

Use the modulo operator.

if(i % 3 == 0)

Also see Modulo operation at Wikipedia

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 MOD operator

for(int i=0; i<24;  i++){
   if( i%3 == 0 )
       // It is divisible by 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.

检查我的剩余部分3

if (i % 3 == 0) {}

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
if( i % 3 == 0 )

%运算符为您提供i / 3的其余部分

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM