blob: e2d329099bf7483d2f09f48ade59e834cd6b7555 [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001// SPDX-License-Identifier: GPL-2.0
Davidlohr Bueso30493cc2013-04-29 16:18:09 -07002/*
3 * Copyright (C) 2013 Davidlohr Bueso <davidlohr.bueso@hp.com>
4 *
5 * Based on the shift-and-subtract algorithm for computing integer
6 * square root from Guy L. Steele.
7 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07008
9#include <linux/kernel.h>
Paul Gortmaker8bc3bcc2011-11-16 21:29:17 -050010#include <linux/export.h>
Peter Zijlstraf8ae1072017-11-17 15:28:08 -080011#include <linux/bitops.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070012
13/**
Peter Zijlstrae813a612017-11-17 15:28:12 -080014 * int_sqrt - computes the integer square root
Linus Torvalds1da177e2005-04-16 15:20:36 -070015 * @x: integer of which to calculate the sqrt
16 *
Peter Zijlstrae813a612017-11-17 15:28:12 -080017 * Computes: floor(sqrt(x))
Linus Torvalds1da177e2005-04-16 15:20:36 -070018 */
19unsigned long int_sqrt(unsigned long x)
20{
Davidlohr Bueso30493cc2013-04-29 16:18:09 -070021 unsigned long b, m, y = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -070022
Davidlohr Bueso30493cc2013-04-29 16:18:09 -070023 if (x <= 1)
24 return x;
Linus Torvalds1da177e2005-04-16 15:20:36 -070025
Peter Zijlstraf8ae1072017-11-17 15:28:08 -080026 m = 1UL << (__fls(x) & ~1UL);
Davidlohr Bueso30493cc2013-04-29 16:18:09 -070027 while (m != 0) {
28 b = y + m;
29 y >>= 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -070030
Davidlohr Bueso30493cc2013-04-29 16:18:09 -070031 if (x >= b) {
32 x -= b;
33 y += m;
Linus Torvalds1da177e2005-04-16 15:20:36 -070034 }
Davidlohr Bueso30493cc2013-04-29 16:18:09 -070035 m >>= 2;
Linus Torvalds1da177e2005-04-16 15:20:36 -070036 }
Davidlohr Bueso30493cc2013-04-29 16:18:09 -070037
38 return y;
Linus Torvalds1da177e2005-04-16 15:20:36 -070039}
40EXPORT_SYMBOL(int_sqrt);