square_root
square_rootは、unsigned longを取り、その平方根を返す関数です。あるいは、もし根が整数でなければ、次の整数に切り上げられます。
#include <dlib / algs.h>
inline unsigned long square_root (
unsigned long value
)
/*!
requires
- value <= 2^32 - 1
ensures
- returns the square root of value. if the square root is not an
integer then it will be rounded up to the nearest integer.
!*/
{
unsigned long x;
// set the initial guess for what the root is depending on
// how big value is
if (value < 3)
return value;
else if (value < 4096) // 12
x = 45;
else if (value < 65536) // 16
x = 179;
else if (value < 1048576) // 20
x = 717;
else if (value < 16777216) // 24
x = 2867;
else if (value < 268435456) // 28
x = 11469;
else // 32
x = 45875;
// find the root
x = (x + value/x)>>1;
x = (x + value/x)>>1;
x = (x + value/x)>>1;
x = (x + value/x)>>1;
if (x*x < value)
return x+1;
else
return x;
}