mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
优化NumberUtil.isPrime()方法:
1.优化执行过程, 直接排除偶数; 2.修改函数名, 从复数形式变为单数;
This commit is contained in:
parent
19d9717e49
commit
bb29b97849
@ -805,9 +805,16 @@ public class NumberUtil {
|
||||
* @param n 数字
|
||||
* @return 是否是质数
|
||||
*/
|
||||
public static boolean isPrimes(final int n) {
|
||||
public static boolean isPrime(final int n) {
|
||||
Assert.isTrue(n > 1, "The number must be > 1");
|
||||
for (int i = 2; i <= Math.sqrt(n); i++) {
|
||||
if (n <= 3) {
|
||||
return true;
|
||||
} else if ((n & 1) == 0) {
|
||||
// 快速排除偶数
|
||||
return false;
|
||||
}
|
||||
final int end = (int) Math.sqrt(n);
|
||||
for (int i = 3; i <= end; i += 2) {
|
||||
if (n % i == 0) {
|
||||
return false;
|
||||
}
|
||||
|
@ -459,4 +459,18 @@ public class NumberUtilTest {
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
NumberUtil.range(0, Integer.MIN_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isPrimeTest(){
|
||||
Assert.assertTrue(NumberUtil.isPrime(2));
|
||||
Assert.assertTrue(NumberUtil.isPrime(3));
|
||||
Assert.assertTrue(NumberUtil.isPrime(7));
|
||||
Assert.assertTrue(NumberUtil.isPrime(17));
|
||||
Assert.assertTrue(NumberUtil.isPrime(296731));
|
||||
Assert.assertTrue(NumberUtil.isPrime(99999989));
|
||||
|
||||
Assert.assertFalse(NumberUtil.isPrime(4));
|
||||
Assert.assertFalse(NumberUtil.isPrime(296733));
|
||||
Assert.assertFalse(NumberUtil.isPrime(20_4123_2399));
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user