int_sqrt.c 1.13 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
2 3 4 5 6 7
/*
 * Copyright (C) 2013 Davidlohr Bueso <davidlohr.bueso@hp.com>
 *
 *  Based on the shift-and-subtract algorithm for computing integer
 *  square root from Guy L. Steele.
 */
Linus Torvalds's avatar
Linus Torvalds committed
8 9

#include <linux/kernel.h>
10
#include <linux/export.h>
11
#include <linux/bitops.h>
Linus Torvalds's avatar
Linus Torvalds committed
12 13

/**
14
 * int_sqrt - computes the integer square root
Linus Torvalds's avatar
Linus Torvalds committed
15 16
 * @x: integer of which to calculate the sqrt
 *
17
 * Computes: floor(sqrt(x))
Linus Torvalds's avatar
Linus Torvalds committed
18 19 20
 */
unsigned long int_sqrt(unsigned long x)
{
21
	unsigned long b, m, y = 0;
Linus Torvalds's avatar
Linus Torvalds committed
22

23 24
	if (x <= 1)
		return x;
Linus Torvalds's avatar
Linus Torvalds committed
25

26
	m = 1UL << (__fls(x) & ~1UL);
27 28 29
	while (m != 0) {
		b = y + m;
		y >>= 1;
Linus Torvalds's avatar
Linus Torvalds committed
30

31 32 33
		if (x >= b) {
			x -= b;
			y += m;
Linus Torvalds's avatar
Linus Torvalds committed
34
		}
35
		m >>= 2;
Linus Torvalds's avatar
Linus Torvalds committed
36
	}
37 38

	return y;
Linus Torvalds's avatar
Linus Torvalds committed
39 40
}
EXPORT_SYMBOL(int_sqrt);
41 42 43 44 45 46 47 48 49 50 51 52 53 54

#if BITS_PER_LONG < 64
/**
 * int_sqrt64 - strongly typed int_sqrt function when minimum 64 bit input
 * is expected.
 * @x: 64bit integer of which to calculate the sqrt
 */
u32 int_sqrt64(u64 x)
{
	u64 b, m, y = 0;

	if (x <= ULONG_MAX)
		return int_sqrt((unsigned long) x);

55
	m = 1ULL << ((fls64(x) - 1) & ~1ULL);
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
	while (m != 0) {
		b = y + m;
		y >>= 1;

		if (x >= b) {
			x -= b;
			y += m;
		}
		m >>= 2;
	}

	return y;
}
EXPORT_SYMBOL(int_sqrt64);
#endif