Skip to content

Commit 46c62dc

Browse files
sqrt
Signed-off-by: Leo Ma <[email protected]>
1 parent 48af54f commit 46c62dc

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

069_sqrt/Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test sqrt.c

069_sqrt/sqrt.c

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
static int mySqrt(int x)
5+
{
6+
if (x == 0) {
7+
return 0;
8+
}
9+
10+
unsigned int left = 1;
11+
unsigned int right = (unsigned int) x;
12+
for (; ;) {
13+
unsigned int mid = left + (right - left) / 2;
14+
if (mid > x/mid) {
15+
right = mid;
16+
} else {
17+
if (mid + 1 > x/(mid + 1)) {
18+
return mid;
19+
} else {
20+
left = mid;
21+
}
22+
}
23+
}
24+
}
25+
26+
int main(int argc, char **argv)
27+
{
28+
if (argc != 2) {
29+
fprintf(stderr, "Usage: ./test n\n");
30+
exit(-1);
31+
}
32+
33+
printf("%d\n", mySqrt(atoi(argv[1])));
34+
return 0;
35+
}

0 commit comments

Comments
 (0)