Blame view

lib/int_sqrt.c 688 Bytes
b24413180   Greg Kroah-Hartman   License cleanup: ...
1
  // SPDX-License-Identifier: GPL-2.0
30493cc9d   Davidlohr Bueso   lib/int_sqrt.c: o...
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.
   */
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
8
9
  
  #include <linux/kernel.h>
8bc3bcc93   Paul Gortmaker   lib: reduce the u...
10
  #include <linux/export.h>
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
11
12
13
14
15
16
17
18
19
  
  /**
   * int_sqrt - rough approximation to sqrt
   * @x: integer of which to calculate the sqrt
   *
   * A very rough approximation to the sqrt() function.
   */
  unsigned long int_sqrt(unsigned long x)
  {
30493cc9d   Davidlohr Bueso   lib/int_sqrt.c: o...
20
  	unsigned long b, m, y = 0;
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
21

30493cc9d   Davidlohr Bueso   lib/int_sqrt.c: o...
22
23
  	if (x <= 1)
  		return x;
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
24

30493cc9d   Davidlohr Bueso   lib/int_sqrt.c: o...
25
26
27
28
  	m = 1UL << (BITS_PER_LONG - 2);
  	while (m != 0) {
  		b = y + m;
  		y >>= 1;
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
29

30493cc9d   Davidlohr Bueso   lib/int_sqrt.c: o...
30
31
32
  		if (x >= b) {
  			x -= b;
  			y += m;
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
33
  		}
30493cc9d   Davidlohr Bueso   lib/int_sqrt.c: o...
34
  		m >>= 2;
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
35
  	}
30493cc9d   Davidlohr Bueso   lib/int_sqrt.c: o...
36
37
  
  	return y;
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
38
39
  }
  EXPORT_SYMBOL(int_sqrt);