2

Using a batch script I would like to check if the number a user enters is a perfect square and if not find the closest number that is a perfect square.

@echo off  && cls 
Set /p input=
if %input% == PERFECT SQUARE echo perfect square
If %input% not == PERFECT SQUARE do (
::find closest perfect square
Magoo
  • 77,302
  • 8
  • 62
  • 84
jonathan x
  • 141
  • 1
  • 8

2 Answers2

3

EDIT: I made a small mod. to get the closest perfect square, instead of the smallest.

@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%
Aacini
  • 65,180
  • 12
  • 72
  • 108
1
@echo off && cls
setlocal enabledelayedexpansion

set /p input=

set j=0
for /l %%i in (0,1,%input%) do (
  set /a test=%%i*%%i
  if !test! equ %input% (
    echo perfect square
    goto:brk1
  )
  if !test! gtr %input% (
    set /a delta=!test!-!input!
    set /a test0=!j!*!j!
    set /a delta0=!input!-!test0!
    if !delta0! lss !delta! (set /a s=!j!) else (set /a s=%%i)
    set /a result=!s!*!s!
    echo closest perfect square: !result!
    goto:brk1
  )
  set j=%%i
)
:brk1
kay27
  • 897
  • 7
  • 16