Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  * Copyright (C) 2013 Davidlohr Bueso <davidlohr.bueso@hp.com>
0004  *
0005  *  Based on the shift-and-subtract algorithm for computing integer
0006  *  square root from Guy L. Steele.
0007  */
0008 
0009 #include <linux/export.h>
0010 #include <linux/bitops.h>
0011 #include <linux/limits.h>
0012 #include <linux/math.h>
0013 
0014 /**
0015  * int_sqrt - computes the integer square root
0016  * @x: integer of which to calculate the sqrt
0017  *
0018  * Computes: floor(sqrt(x))
0019  */
0020 unsigned long int_sqrt(unsigned long x)
0021 {
0022     unsigned long b, m, y = 0;
0023 
0024     if (x <= 1)
0025         return x;
0026 
0027     m = 1UL << (__fls(x) & ~1UL);
0028     while (m != 0) {
0029         b = y + m;
0030         y >>= 1;
0031 
0032         if (x >= b) {
0033             x -= b;
0034             y += m;
0035         }
0036         m >>= 2;
0037     }
0038 
0039     return y;
0040 }
0041 EXPORT_SYMBOL(int_sqrt);
0042 
0043 #if BITS_PER_LONG < 64
0044 /**
0045  * int_sqrt64 - strongly typed int_sqrt function when minimum 64 bit input
0046  * is expected.
0047  * @x: 64bit integer of which to calculate the sqrt
0048  */
0049 u32 int_sqrt64(u64 x)
0050 {
0051     u64 b, m, y = 0;
0052 
0053     if (x <= ULONG_MAX)
0054         return int_sqrt((unsigned long) x);
0055 
0056     m = 1ULL << ((fls64(x) - 1) & ~1ULL);
0057     while (m != 0) {
0058         b = y + m;
0059         y >>= 1;
0060 
0061         if (x >= b) {
0062             x -= b;
0063             y += m;
0064         }
0065         m >>= 2;
0066     }
0067 
0068     return y;
0069 }
0070 EXPORT_SYMBOL(int_sqrt64);
0071 #endif