2
* Copyright (C) 2017 Denys Vlasenko <vda.linux@googlemail.com>
4
* Licensed under GPLv2, see file LICENSE in this source tree.
7
//kbuild:lib-y += isqrt.o
12
/* gcc -DISQRT_TEST -Wall -O2 isqrt.c -oisqrt && ./isqrt $((RANDOM*RANDOM)) */
16
# define FAST_FUNC /* nothing */
19
/* Returns such x that x+1 > sqrt(N) */
20
unsigned long FAST_FUNC isqrt(unsigned long long N)
24
#define LL_WIDTH_BITS (unsigned)(sizeof(N)*8)
26
shift = LL_WIDTH_BITS - 2;
30
if ((unsigned long long)x * x > (N >> shift))
31
x--; /* whoops, that +1 was too much */
33
} while ((int)shift >= 0);
38
int main(int argc, char **argv)
40
unsigned long long n = argv[1] ? strtoull(argv[1], NULL, 0) : time(NULL);
46
printf("isqrt(%llx)=%lx\n", n, h);
47
if ((unsigned long long)h * h > n) {
48
printf("BAD1: isqrt(%llx)=%lx\n", n, h);
52
if ((unsigned long long)h * h != 0 /* this can overflow to 0 - not a bug */
53
&& (unsigned long long)h * h <= n)
55
printf("BAD2: isqrt(%llx)=%lx\n", n, h);