From 46c62dc5a7e2057bd20de431e3d792d37597204e Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Thu, 5 Oct 2017 07:34:06 +0800 Subject: [PATCH] sqrt Signed-off-by: Leo Ma --- 069_sqrt/Makefile | 2 ++ 069_sqrt/sqrt.c | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 069_sqrt/Makefile create mode 100644 069_sqrt/sqrt.c diff --git a/069_sqrt/Makefile b/069_sqrt/Makefile new file mode 100644 index 0000000..3d94c52 --- /dev/null +++ b/069_sqrt/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test sqrt.c diff --git a/069_sqrt/sqrt.c b/069_sqrt/sqrt.c new file mode 100644 index 0000000..1d3a5c3 --- /dev/null +++ b/069_sqrt/sqrt.c @@ -0,0 +1,35 @@ +#include +#include + +static int mySqrt(int x) +{ + if (x == 0) { + return 0; + } + + unsigned int left = 1; + unsigned int right = (unsigned int) x; + for (; ;) { + unsigned int mid = left + (right - left) / 2; + if (mid > x/mid) { + right = mid; + } else { + if (mid + 1 > x/(mid + 1)) { + return mid; + } else { + left = mid; + } + } + } +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test n\n"); + exit(-1); + } + + printf("%d\n", mySqrt(atoi(argv[1]))); + return 0; +}