:: Prime.bat - Generate a serial prime number
:: Dirk van Deun - Will Sort Modified 2004/11/18
::
:: Contents of reference:
:: A system of batch files that generates prime numbers in "prisoners
:: notation". (It's rather sloooooooow.) END.BAT is really an empty
:: file, by the way.
:: http://student.vub.ac.be/~dvandeun
::
:: 素数堆垒程序修改版: 一个产生素数的程序, 因为其输出形似堆垒而名
::
:: 源代码正如上文所说,非常的慢,所以不得不做了一些修改
::
:: 主要的修改:
:: 1 将源码的所有函数并入主程序中, 加套控制性外壳
:: 2 将主循环起始值改为3, 步进值改为2, 也即只判断大于2的奇数
:: 3 判断素数时, 不再除以从2到n-1的所有数, 改为从2到n-1的所有素数
:: 4 将除法函数的递归相减算法改为循环相减算法
:: 5 将素数判断循环和除法循环并入主循环
:: 6 变量名, 标签名, 注释, 缩进等代码风格上的改动
::
:: 环境变量说明:
:: iTest:测试数, iPrime:素数序号
:: divisor:用以判断素数的除数, iDivisor:除数序号
:: less: 除法中不足除的标志
::
@echo off
if == goto %2
if == %comspec% /e:4096 /c %0 $ init
del ~prime.bat
goto end:: 初始化: 产生素数2, 将它存为第一个素数, 设置循环起始值为3
:init
set iTest=I
set iPrime=I
set %iPrime%=I I
echo I I:: 对3~n的奇数 %iTest% 与已产生的所有素数由小到大循环相除
:: 若全部未整除则显示此整数, 否则递增 %iTest% 后继续循环
:MainLoop
set iTest=I I %iTest%
set iDivisor=I

rimeLoop
echo set divisor=%%%iDivisor%%%>~prime.bat
call ~prime.bat
call %0 $ Divide %iTest%
if "%less%"=="" goto MainLoop
if "%iDivisor%"=="%iPrime%" goto IsPrime
set iDivisor=I%iDivisor%
goto PrimeLoop
:IsPrime
echo %iTest%
set iPrime=I%iPrime%
if "%iPrime%"=="IIIIIIIIIIII" goto end
set %iPrime%=%iTest%
goto MainLoop:: 将传入的被除数 %iTest% 除以(循环减)除数 %divisor%
:: 若不足除 (无法整除) 则返回不足信号 less, 否则直接返回

ivide
for %%n in (%divisor%) do shift
if not == goto Divide
set less=
if == set less=true
goto end:end