Skip to content

Commit

Permalink
判断是否是质数
Browse files Browse the repository at this point in the history
  • Loading branch information
Xikl committed Apr 25, 2020
1 parent b98392c commit ef74e40
Showing 1 changed file with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.ximo.datastructuresinaction.algorithmsfourthedition;

/**
* @author xikl
* @date 2020/4/25
*/
public class Chapter01 {

public static boolean isPrime(int n) {
// 大于1的数字才是
if (n < 2) {
return false;
}

// 2 和 3 本身只有1和本身
if (n == 2 || n == 3) {
return true;
}

// 排除偶数
if (n % 2 == 0) {
return false;
}

// 根据定理
// 避免求根号,改为平方
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}

return true;
}

public static void main(String[] args) {
System.out.println(isPrime(13));
}


}

0 comments on commit ef74e40

Please sign in to comment.