Read Mode

How To calculate Sqrt of a Number in Batch ?? (for begginers)

Calculating Sqrt
Calculating SquareRoot (sqrt) of a Number is a Difficult and very time consuming task ,if you are using the traditional 'long Division method' and if you have very less practice of the method...then it may become pain in the butt. Moreover ,if you want to make such a batch program that can calculate sqrt for you..then you need to have a different point of approach...

In this Post i'm Gonna tell you how to make a simple Batch Program that can calculate the sqrt of a number (that you'll enter in it). The Different approach here is , in the method of calculation... as I'm not telling computer that how to use long division method ,rather I'm using alternate method ...

If a number is perfect square (e.g. 4,16,25 ...) then if we subtract odd numbers series elements (e.g. 1,3,5,7 ...) then at last we get perfect '0' ...otherwise the number is not a perfect square and it needs to be calculated only by long division... I'm using a loop to calculate sqrt of perfect squares...and I'm using vbs (instead of defining long division) to fulfill my requirement ... 
If you read the code carefully ,you'll know how the program works...and you even can't recognize that ..i'm using vbs for calculating sqrt of non-prefect squares... :)

Code :

@echo off
Title Sqrt Calculator... by Kvc
set /p "no=Enter The Number to calculate Sqrt : "
if not defined no goto top
set /a "no=%no%"
set sub=1
set sqrt=0
set bkup=%no%

Rem Calculating Sqrt here....
Rem Using Property of Perfect sqr, that we have learned in small Classes...that if we subtract odd nos. from perfect sqr,then
rem atlast perfect '0' will be left otherwise not.... :]

if %no% gtr 0 (
set /a no=%no%-%sub%
set /a sub+=2
set /a sqrt+=1
goto loop
goto end

REM Checking if the answer is cmd doesn't support float values.... :[

set /a sqr=%sqrt%*%sqrt%
if "%sqr%" == "%bkup%" (
Echo. Sqrt : %sqrt%
) ELSE (
echo. wscript.echo %bkup%^^(1/2^) >"%tmp%\a.vbs"
for /f "skip=3 tokens=*" %%a in ('cscript "%tmp%\a.vbs"') do echo. %%a
Del /q "%tmp%\a.vbs"
goto top

rem #kvc
-------------------------code ends-----------------

Download Batch File Here : Sqrt Calculator by Kvc


  1. Script Idea: If it is a decimal (not a perfect square) it tries to split it apart until it finds a perfect square??

    1. Yes Maps!

      That is why - This is a basic beginner's article for understanding various other concepts. :)

  2. Oh nice! This is good stuff for my calculator with buttons! Thank you. I've a question. Could you explain how to calcuate decimals, or is that to difficult? ;)

    1. This is just a basic intro for new Programmers. And, Example for - How simple algorithms can be created in a computer program.

      For Creating a calculator - you should try to use Great AC function for the Precise mathematical calculations. Hope, This will help you out. :)


Powered by Blogger.