How to check if an integer can be divided by 3

后端 未结 8 1082
不知归路
不知归路 2020-12-29 03:47

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,         


        
相关标签:
8条回答
  • 2020-12-29 04:18

    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.

    0 讨论(0)
  • 2020-12-29 04:21

    Use the modulo operator.

    if(i % 3 == 0)
    

    Also see Modulo operation at Wikipedia

    0 讨论(0)
  • 2020-12-29 04:31

    Check the remainder of i devided by 3

    if (i % 3 == 0) {}
    
    0 讨论(0)
  • 2020-12-29 04:36

    Use the MOD operator

    for(int i=0; i<24;  i++){
       if( i%3 == 0 )
           // It is divisible by 3
    
    }
    
    0 讨论(0)
  • 2020-12-29 04:37
    if( i % 3 == 0 )
    

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

    0 讨论(0)
  • 2020-12-29 04:38

    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.

    0 讨论(0)
提交回复
热议问题