I am so new in C and so far I didn't comprehend how to prevent from integer overflow, I read many articles but still I am not 100% sure! in this case
int ft_sqrt(int nb)
{
long int sqrt;
if (nb <= 0)
return (0);
if (nb == 1)
return (1);
sqrt = 1;
while (sqrt * sqrt < nb)
{
sqrt++;
}
if (sqrt * sqrt == nb)
return (sqrt);
else
return (0);
}
to prevent overflow should I use
long
? what is the best practice to do that?
longis just a short name forlong int. On some compilers and systems,longis 32 bits, on others it's 64 bits. To make sure you get the largest integer type, uselong longwhich is guaranteed to be at least 64 bits. If you're dealing with numbers larger than 64-bit integers can handle, then there are "bignum" libraries you can use.sqrt, as it is a name of a standard function.sqrt * sqrtmay "overflow", you will need to check thatsqrtis less than (or equal) the square root maximum valuelong intcan hold before performing the operation.while (sqrt < nb / sqrt)— that doesn't overflow. Check that the loop breaks or continues correctly on equality (<vs<=). You should be able to do better than incrementingsqrtby one each iteration. Look up Newton-Raphson, for example.intis 46,341, not 2^16.