long
不一定比int
宽,因此使用它可能不会扩大计算范围.
为了避免溢出,不要相乘,而要除法.
int ft_sqrt(int nb) {
int sqrt;
if (nb <= 0)
return (0);
if (nb == 1)
return (1);
sqrt = 1;
// while (sqrt * sqrt < nb)
while (sqrt < nb / sqrt) {
sqrt++;
}
if (sqrt == nb / sqrt)
return (sqrt);
else
return (0);
}
是的,代码的性能会受到影响-但OP算法有很多改进的方法)
备用代码:
unsigned bit_width(unsigned x) {
unsigned width = 0;
while (x) {
x /= 2;
width++;
}
return width;
}
unsigned usqrt(unsigned x) {
if (x == 0) {
return 0;
}
unsigned y = 1u << bit_width(x) / 2;
unsigned y_previous;
unsigned diff;
unsigned diff1count = 0;
do {
y_previous = y;
y = (y + x / y) / 2;
diff = y_previous < y ? y - y_previous : y_previous - y;
if (diff == 1)
diff1count++;
} while (diff > 1 || (diff == 1 && diff1count <= 1));
y = (y_previous + y) / 2;
return y;
}