Skip to content

Instantly share code, notes, and snippets.

@tianyk
Created June 10, 2022 09:43
Show Gist options
  • Save tianyk/ec60d3ae268d3784a8d4e2f98bb905df to your computer and use it in GitHub Desktop.
Save tianyk/ec60d3ae268d3784a8d4e2f98bb905df to your computer and use it in GitHub Desktop.
素数
public class PrimeNumber {
/**
* 判断是否为素数
*
* 只能被1和本身整除的数字为素数
*
* @param n
* @return
*/
public static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i < n; ++i) {
// 如果能被其它数字整除,则不是素数。提前结束循环,返回false
if (n % i == 0) {
return false;
}
}
// 经过上面的循环,没有发现有被整除的数字。说明是素数,返回 true
return true;
}
public static void main(String[] args) {
int end = 100;
// 循环 从2开始,到某个数字结束
for (int num = 2; num < end; num++) {
if (isPrime(num)) {
System.out.println("num:" + num);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment