heron_sqrt/bericht/code/sqrt.c

31 lines
586 B
C
Raw Normal View History

2014-01-13 08:08:21 +00:00
typedef uint32_t u32;
// have to a multiply of 2
#define COMMA 8 @\label{comma}@
#define COMMA_FIX (COMMA >> 1)
void heron_sqrt(u32 *mem) {
int i = mem[0];
while (i > 0) {
u32 s = mem[i];
u32 x = s;
if (s > 1) {
// x_0 = (s + 1) / 2
// without increment to avoid overflow for 0xffffffff
x = x >> 1;
u32 old_x = x;
while(1) {
// x_{n + 1} = (x_n + (s / x_n)) / 2
x = (x >> 1) + ((s/x) >> 1);
if (old_x <= x) {
break;
}
old_x = x;
}
}
mem[i] = x << COMMA_FIX;
i--;
}
}