Java 如何检查一个整数是否可以被3整除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6647296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if an integer can be divided by 3
提问by Leem
How to check if my integer can be divided by 3 as below:
如何检查我的整数是否可以除以 3,如下所示:
for(int i=0; i<24; i++){
//here, how to check if "i" can be divided by 3 completely(e.g. 3, 6, 15)?
}
采纳答案by Sebastian Wramba
回答by Talha Ahmed Khan
Use the MOD operator
使用 MOD 运算符
for(int i=0; i<24; i++){
if( i%3 == 0 )
// It is divisible by 3
}
回答by Dimitar Petrov
Check the remainder of i devided by 3
检查 i 除以 3 的余数
if (i % 3 == 0) {}
回答by Tim Meyer
if( i % 3 == 0 )
The % operator delivers you the rest of the division i / 3
% 运算符为您提供除 i / 3 的其余部分
回答by BudgieInWA
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.
%
被称为“mod”或“模数”,并在将两个数字相除时为您提供余数。
These are all true:
这些都是真的:
6 % 3 == 0
7 % 3 == 1
7 % 4 == 3
回答by Benny Tjia
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?
这个问题是真的吗?
回答by Peter Lawrey
If you are using a loop, you can use the fact that every third number can be divided by 3.
如果您使用的是循环,则可以使用每三个数字可以被 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.
这避免了对模数的需要,并将循环数减少了 3 倍。
回答by Thomas Mueller
Well, what you coulddo (it mightbe 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.
但是,乘法技巧仅适用于-2 <= i <= 1610612735
。这个答案的灵感来自这个优化问题。但如果我可以给你一个提示:使用(i % 3) == 0
. 它非常简单,并且将始终有效。