I didn't properly understood how this code is working

this is the square root program without using sqrt function.
Also I wanted to ask that is it really necessary to use this approach, I mean using sqrt will save us time in competitive programming.

Hey @shazanahmed1
Yes you have to use sqrt() inbuilt in competitive
You are doing it this way to lnow how things work in background.

The above code is quite basic
Say we have to find sqrt of 10
Then we check 1*1<=10 increment
2*2<=10 we increment
3*3<=10 we increment
Now 4*4>10 so we stop
And see its 1 more than required ans so we do ans- -
Hence ans =3

I totally understood that but can you please show the dry run for the following code. That how each variables are working.

Hey @shazanahmed1
There is only one variable in your current code i.e ans and I already showed you its dry run in previous comment

Lets do it again for say N =20
Ans =0 initially and inc=1
Loop
0*0<=20 ans+=inc
1*1<=20 ans+=inc
2*2<=20 ans+=inc
3*3<=20 ans+=inc
4*4<=20 ans+=inc
5*5>20 we stop

And decrement ans-=inc
Ans=4

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.