讲究效率的话,应该用Sieve of Eratosthenes(埃拉托斯特尼筛法),但是代码比较长- @ECHO OFF
- SETLOCAL ENABLEDELAYEDEXPANSION
-
- REM Author: Demon
- REM Date: 2011/5/29
- REM Website: http://demon.tw
- REM Algorithm: Sieve of Eratosthenes
- REM Reference: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
-
- SET /A limit = 1000
- SET /A prime = 2
-
- CALL :Init
- CALL :SievePrime
- CALL :Display
- PAUSE & GOTO :EOF
-
- :Display
- FOR /L %%i IN (2, 1, %limit%) DO (
- SET t=!arr[%%i]!
- IF !t! NEQ 0 ECHO !t!
- )
- GOTO :EOF
-
- :Init
- FOR /L %%i IN (1, 1, %limit%) DO SET arr[%%i]=%%i
- GOTO :EOF
-
- :SievePrime
- SET /A pow = prime * prime
- IF %pow% LSS %limit% (
- SET /A n = prime * 2
- FOR /L %%i IN (!n!, %prime%, %limit%) DO SET arr[%%i]=0
- CALL :NextPrime
- GOTO :SievePrime
- )
- GOTO :EOF
-
- :NextPrime
- SET /A prime += 1
- FOR /L %%i IN (%prime%, 1, %limit%) DO (
- IF !arr[%%i]! NEQ 0 SET /A prime = %%i & GOTO :EOF
- )
- GOTO :EOF
复制代码
|