mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
!869 优化NumberUtil.isPrimes()方法
Merge pull request !869 from emptypoint/update-NumberUtil.isPrime
This commit is contained in:
commit
4aba88e828
@ -805,9 +805,16 @@ public class NumberUtil {
|
|||||||
* @param n 数字
|
* @param n 数字
|
||||||
* @return 是否是质数
|
* @return 是否是质数
|
||||||
*/
|
*/
|
||||||
public static boolean isPrimes(final int n) {
|
public static boolean isPrime(final int n) {
|
||||||
Assert.isTrue(n > 1, "The number must be > 1");
|
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) {
|
if (n % i == 0) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
@ -459,4 +459,18 @@ public class NumberUtilTest {
|
|||||||
//noinspection ResultOfMethodCallIgnored
|
//noinspection ResultOfMethodCallIgnored
|
||||||
NumberUtil.range(0, Integer.MIN_VALUE);
|
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