2016-03-02 44 views
0

我正在尝试在批处理中编写一个程序,将数字放入简化的激进形式。有没有办法检查一个数字是否是一个完美的正方形?是否有BATCH/CMD命令检查数字是否是完美的正方形?

+0

停止写作批次,有很大的选择 – Marged

+1

翻译:“我不知道如何在批量解决这个问题,所以你需要学习不同的语言。” - [Marged](http://stackoverflow.com/users/1354537/marged) – rojo

+0

@rojo:优秀的评论! **'+ oo' ** – Aacini

回答

2

最简单的方法是用与接受打印张数是或否取决于如果数量为方形或不并设置1 ERRORLEVEL如果它是一个子程序嵌入的JScript code.Here的例子:

@echo off 

call :isSquare 81 
call :isSquare 7 
call :isSquare 9 

if errorlevel 1 (
    echo 9 is a square number 
) 
exit /b %errorlevel% 


:isSquare 
setlocal 
set /a number=%~1 

:: Define simple macros to support JavaScript within batch 
set "beginJS=mshta "javascript:code(close(new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write(" 
set "endJS=)));"" 



:: FOR /F does not need pipe 
for /f %%N in (
    '%beginJS% Math.sqrt(%number%) %endJS%' 
) do set sqrt=%%N 

if "%sqrt%" equ "%sqrt:.=%" (
    echo Yep! 
    endlocal & exit /b 1 

) else (
    echo Nope! 
    endlocal & exit /b 0 
) 

endlocal 

现在我想的是纯粹的单批溶液(可检查所有34bit平方数列表?)

+1

击败纯粹的批次解决方案。 ':)' – rojo

2

最简单的方法是使用PowerShell命令。

@echo off 
setlocal 

call :isSquare 25 && (
    echo The square root is an integer. 
) || (
    echo The square root is a float. 
) 

goto :EOF 

:isSquare <num> 
for /f "tokens=2 delims=." %%I in ('powershell "[math]::Sqrt(%1)"') do exit /b 1 
exit /b 0 

它比npocmaka的JScript的宏观慢,但。


以下是基于algorithm found on Wikipedia的纯批处理解决方案。 (有关详细信息,请参见标有“二进制数字系统(基数2)”的部分。)如果数字是完美平方,:sqrt函数会设置错误级别0,如果不是,则为非零;并为结果设置一个变量。这很快。

@echo off 
setlocal 

set num=2147395600 

call :sqrt %num% foo && (
    call echo The square root of %num% is %%foo%% 
) || (
    echo %num% is not a perfect square 
) 

goto :EOF 

:sqrt <num> <return_var> 
setlocal enabledelayedexpansion 
set /a "res = 0, bit = 1 << 30, num = %~1" 

:sqrt_loop1 
if %bit% gtr %num% (
    set /a "bit >>= 2" 
    goto :sqrt_loop1 
) 

:sqrt_loop2 
if %bit% neq 0 (
    set /a resbit = res + bit 
    if %num% geq !resbit! (
     set /a "num -= resbit, res >>= 1, res += bit" 
    ) else set /a "res >>= 1" 
    set /a "bit >>= 2" 
    goto sqrt_loop2 
) 

set /a "ret = %~1 - (res * res)" 
endlocal & set "%~2=%res%" & exit /b %ret% 
+1

非常好:) ... – npocmaka

2

下纯批处理文件解决方案,出现在this question,还可以获得最接近完美的正方形,如果给定的数字是不是一个。

@echo off 
setlocal 

cls 
set /P "N=Enter a number: " 

set /A "x=N/(11*1024)+40, x=(N/x+x)>>1, x=(N/x+x)>>1, x=(N/x+x)>>1, x=(N/x+x)>>1, x=(N/x+x)>>1, x+=(N-x*x)>>31, M=x*x" 

if %N% equ %M% (
    echo %N% is perfect square 
    goto :EOF 
) 

set /A "I=(x+1)*(x+1), ID=I-N, MD=N-M" 
if %ID% lss %MD% set M=%I% 
echo The closest perfect square is %M%