This code is not guaranteed by the C ++ standard to work as desired.
Some low-quality math libraries do not return correctly rounded values ββfor pow , even if the inputs have integer values, and the math result can be accurately represented. sqrt can also return an inaccurate value, although this function is easier to implement and therefore less likely to suffer from defects.
Thus, it is not guaranteed that j is an integer if you expect it to be.
In a quality math library, pow and sqrt will always return the correct results (zero error) when the math result is accurately represented. If you have a quality implementation in C ++, this code should work as you wish, up to the limits of integer types and floating point types used.
Code improvement
There is no reason to use pow in this code; std::pow(i, 2) must be i*i . This leads to exact arithmetic (up to the whole overflow) and completely eliminates the question of the correctness of pow .
Removing pow leaves only sqrt . If we know that the implementation returns the correct values, we can accept the use of sqrt . If not, we can use this instead:
for (int i = 0; i*i <= value/2; ++i) { int j = std::round(std::sqrt(value - i*i)); if (j*j + i*i == value) result.push_back( { i, j } ); }
This code relies only on sqrt to return a result within .5 that even a low-quality sqrt implementation should provide reasonable input values.
Eric Postpischil
source share