题目:
统计所有小于非负整数n的质数的数量。
示例:
输入:10
输出:4
解释:小于10的质数一共有4个,它们是2,3,5,7
质数定义为一个大于1的自然数,并且因数只有1和它部分,不能整除其他自然数。
class Solution{
public int countPrimes(int n){// 不能写伪代码,要考虑时间复杂度}
}
答案:
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("输入:");
int n = scanner.nextInt();
System.out.println("输出:" + countPrimes(n));
}
// 由于我要测试,所以将此方法设置成了静态方法
public static int countPrimes(int n) {
if (n <= 1) {
throw new RuntimeException("质数是大于1的自然数,所以" + n + "中没有质数");
}
// 计算到底有多个数是质数
int count = 0;
for (int i = 2; i <= n; i++) {
if (judge(i)) count++;
}
return count;
}
// 检查该数是否是质数,上面传过来的数字绝对大于等于2,所以不用不用担心其他情况
private static boolean judge(int num) {
// Math.sqrt()可以找到num的平方根,这样效率更高一点
for (int i = 2; i <= (int) Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}
}
结果:
输入:10
输出:4