FreeNOS
sqrt.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2015 Niek Linnenbank
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "math.h"
19
20u32 sqrt(u32 number)
21{
22 u32 op = number;
23 u32 res = 0;
24 u32 one = 1uL << 30; // The second-to-top bit is set: use 1u << 14 for uint16_t type; use 1uL<<30 for u32 type
25
26 if (number == 0)
27 return 0;
28
29 // "one" starts at the highest power of four <= than the argument.
30 while (one > op)
31 {
32 one >>= 2;
33 }
34
35 while (one != 0)
36 {
37 if (op >= res + one)
38 {
39 op = op - (res + one);
40 res = res + 2 * one;
41 }
42 res >>= 1;
43 one >>= 2;
44 }
45 return res;
46}
u32 sqrt(u32 number)
Compute the square root of a number.
Definition sqrt.cpp:20
unsigned int u32
Unsigned 32-bit number.
Definition Types.h:53