fn sqrt_int(comptime T: type, value: T) Sqrt(T) T: typevalue: T36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62fn sqrt_int(comptime T: type, value: T) Sqrt(T) {
if (@typeInfo(T).int.bits <= 2) {
return if (value == 0) 0 else 1; // shortcut for small number of bits to simplify general case
} else {
const bits = @typeInfo(T).int.bits;
const max = math.maxInt(T);
const minustwo = (@as(T, 2) ^ max) + 1; // unsigned int cannot represent -2
var op = value;
var res: T = 0;
var one: T = 1 << ((bits - 1) & minustwo); // highest power of four that fits into T
// "one" starts at the highest power of four <= than the argument.
while (one > op) {
one >>= 2;
}
while (one != 0) {
const c = op >= res + one;
if (c) op -= res + one;
res >>= 1;
if (c) res += one;
one >>= 2;
}
return @as(Sqrt(T), @intCast(res));
}
}