How do we get Square root of any number Without using sqrt() fuction?

Showing Answers 1 - 5 of 5 Answers

Santosh Kumar

  • Aug 11th, 2006
 

You can use a iterative method for example bisection

#include <stdio.h>
 main()
{
int n;
float eval=1.0,x1=0,x2=n,x; //trying to locate root between x1=0 and x2=n   and giving a initial dummy value to eval
x=(x1+x2)/2;
printf("Enter value for n n n");
scanf("%d",&n);
while((eval > 0.0001 )||( eval < -0.0001) ) { //you can change accuracy by changing 0.0001 to smaller value
eval=  x*x-n;
printf(" eval = %f  t",eval);    //printf to keep track not necessary
if(eval>0){
x2=x;
x=(x2+x1)/2 ;
printf(" x = %f  t",x);  //printf to keep track not necessary
 }
else    {
x1=x ;
x=(x1+x2)/2 ;
printf(" x = %f  t",x); //printf to keep track not necessary
}
printf("n n");
}
printf("the root is =  %f ",x);
      
     
}

  Was this answer useful?  Yes

sathish kumar

  • Aug 14th, 2006
 

#include

main()

{

int a=5;

int b=a**a;

printf("%d", b);

}



I hope the above program would work under Unix. It is not working in Turbo C. If anything wrong in this program please let me know about that through my email.

  Was this answer useful?  Yes

Kiran

  • Aug 21st, 2006
 

#include main(){ int n;float sqr = 0.000001;printf("nEnter any number");scanf("%d",&n);while((sqr*sqr)

  Was this answer useful?  Yes

R.S.Jayasathyanarayanan

  • Dec 17th, 2006
 

#include

main()

{

int a=5;

int b=a^(.5)

tf("%d", b);

}

  Was this answer useful?  Yes

A better approach would be to use newton raphson method. An equivalent python program would be written as:


import sys
import os

i = 0
def sqrt_p(num, prev_sqrt):

global i
i += 1
if ( i > 5 ):
return

curr_sqrt = prev_sqrt - (prev_sqrt * prev_sqrt - num)/(2*prev_sqrt)

print num, curr_sqrt
sqrt_p(num, curr_sqrt)

print "Please enter some number"
data = sys.stdin.readline()

try:
val = float(data)
except ValueError:
print "Please enter a numerical value"
sys.exit()

if ( val < 0 ):
print "Please enter a positive number"
sys.exit()
else:
sqrt_p(val, val/2)

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions