How to check if an integer can be divided by 3

后端 未结 8 1150
不知归路
不知归路 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.

提交回复
热议问题