204. Count Primes

本文介绍了一种计算小于非负整数n的所有素数数量的方法。通过标记法筛选非素数,逐步迭代并跳过已知的合数,提高了算法效率。
Count the number of prime numbers less than a non-negative number, n.

大致思路差不多 答案要简洁一些 注意结束条件 不是 i<num/2 而是i*i<=num 

public int countPrimes(int n) {
    boolean[] notPrime = new boolean[n];
    int count = 0;
    for (int i = 2; i < n; i++) {
        if (notPrime[i] == false) {
            count++;
            for (int j = 2; i*j < n; j++) {
                notPrime[i*j] = true;
            }
        }
    }
    
    return count;
}

it starts from 2, the first prime, then mark the multip of 2 as true in notPrime, so the loop of i will skip them. the next prime is 3, do the same thing. Then it is 4, which 2*2, so the not prime is true, and will skip to next.
### 创建并运行Java程序以计算素数 #### 编写 `CountPrimes.java` 文件 为了实现素数计数功能,首先需要定义一个名为 `CountPrimes` 的类。该类应包含用于判断素数的方法以及主方法来执行逻辑。 ```java public class CountPrimes { public static boolean isPrime(int num) { if (num <= 1) return false; for (int i = 2; i * i <= num; ++i) { if (num % i == 0) return false; } return true; } public static int countPrimesUpTo(int limit) { int primeCount = 0; for (int n = 2; n <= limit; ++n) { if (isPrime(n)) { ++primeCount; } } return primeCount; } public static void main(String[] args) { try { int upperLimit = Integer.parseInt(args[0]); long startTime = System.currentTimeMillis(); int result = countPrimesUpTo(upperLimit); long endTime = System.currentTimeMillis(); System.out.printf("Found %d primes up to %d\n", result, upperLimit); System.out.printf("Execution Time: %.3f seconds%n", ((double)(endTime - startTime))/1000.0); } catch (NumberFormatException | ArrayIndexOutOfBoundsException ex) { System.err.println("Usage: java CountPrimes <integer>"); } } } ``` 此代码段实现了基本的素数检测算法,并接受命令行参数作为上限值,在范围内查找所有素数的同时记录下开始时间和结束时间以便后续计算执行耗时[^1]。 #### 编写 `PrimeCounter.java` 文件 考虑到题目还提到了另一个文件 `PrimeCounter.java`,假设这个文件可能是用来封装更复杂的业务逻辑或者是测试辅助工具。然而基于当前需求描述,仅需关注上述提到的一个主要处理类即可满足要求;如果确实存在其他特定用途,则可以根据实际应用场景调整设计。 因此在此处不再额外提供第二个源文件的内容,而是集中精力于如何构建批处理脚本来调用编译后的 Java 应用程序。 #### 构建 `timeMeasureTest.bat` 批处理文件 接下来创建一个 `.bat` 文件用于自动化编译和运行前面定义好的 Java 类: ```batchfile @echo off setlocal enabledelayedexpansion :: 设置环境变量指向 JDK 安装路径下的 bin 目录(如果有) if not defined JAVA_HOME ( echo ERROR: JAVA_HOME environment variable is not set. exit /b 1 ) :: 清理旧版本 .class 文件 del *.class 2>nul :: 编译 Java 源代码 "%JAVA_HOME%\bin\javac" CountPrimes.java || goto :error :: 运行 Java 程序并传递参数给它 set "inputNumber=1000" echo Running program with input number=%inputNumber% call "%JAVA_HOME%\bin\java" CountPrimes !inputNumber! goto :end :error echo Compilation or execution failed. :end pause ``` 这段批处理脚本会先清理任何现有的 `.class` 文件以防干扰新编译的结果,接着尝试编译 `CountPrimes.java` 并立即运行生成的应用程序实例,同时传入预设的最大数值范围作为输入参数[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值