As @Eugene-Sh said, there is an overflow while computing carre
.
Also, the standard int
is at minimum 16bits. However most of compilers now make it 32bits. So at least you should check the limit, in order your code gets well in all the ways.
Change to long long
to ensure you will have good result, both for carre
and nb
, such that you got 64 bits. But it is only half of the path. as said in a comment, you could still have an overflow when you go over this limit.
So something like this, without changing type:
int max = INT_MAX; // from limits.h
int maxsqrt = sqrt(INT_MAX); // cast to int, such that maxsqrt² is the max square
if (maxsqrt % 2 == 0)
maxsqrt--; // only odd number considered
int maxcarre = maxsqrt*maxsqrt; // this is the max square (carre in french) for an odd INT
Then in your loop, you could now check if carre
is the last one you can compute since maxcarre is the biggest one:
while (carre <= nb)
{
if (nb % i == 0)
return (0);
if (carre >= maxcarre) // this is the last odd square we could compute before overflow
return (-1); // if this -1 represents a "don't" know code for you
carre=carre+4*i+4; // this compute the next square of an odd number
i=i+2;
}
I would recommend however to use at least long
(and therefore changing max to LONG_MAX
) in order to get more capacity and still in the range of the CPU (64 bits on modern compiler), or even long long
since at least it is 64 bits on all compilers.
As @Veltas said: long is 64-bit on some 64-bit compiler implementations. It's not dependant on the OS. Also, IIRC Microsoft's VC++ uses 32-bit long on 64-bit as well.
Thanks to @Veltas, @EugeneSh. and other helping people for their precious feedback!