Distance between two points without using the square root
c, distance, points, square-root
Solution
int int_sqrt(int x){
int s, t;
s = 1; t = x;
while (s < t) {
s <<= 1;
t >>= 1;
}//decide the value of the first tentative
do {
t = s;
s = (x / s + s) >> 1;//x1=(N / x0 + x0)/2 : recurrence formula
} while (s < t);
return t;
}
Problem
Is it possible to calculate the distance between two points without having to use the math.h library? I know that, using the math.h library, it would have to be something among these lines (Euclidean distance formula): ``` int Distance(int x1, int y1, int x2, int y2) { int dx = x2 - x1; int dy = y2 - y1; return sqrt(dx*dx + dy*dy); } ``` However, is there a way of doing this exact same thing but without using the square root (which needs the math.h library)? EDIT: Whenever I try the following code, it gives me Floating Point Exception (Core Dumped): ``` float sqrt(int x) { int i; float s; s=((x/2)+x/(x/2)) / 2; /*first guess*/ for(i=1;i<=4;i++) { /*average of guesses*/ s=(s+x/s)/2; } return s; } float Distance(float x1, float y1, float x2, float y2) { float dx = x2 - x1; float dy = y2 - y1; return sqrt(dx*dx + dy*dy); } int main() { printf("%f", Distance(1, 2, 2, 1)); return 0; } ```