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 when the inputs have integer values and the mathematical result can be exactly represented. sqrt
may also return an inaccurate value, although this function is easier to implement and so less commonly suffers from defects.
Thus, it is not guaranteed that j
is exactly an integer when you might expect it to be.
In a good-quality math library, pow
and sqrt
will always return correct results (zero error) when the mathematical result is exactly representable. If you have a good-quality C++ implementation, this code should work as desired, up to the limits of the integer and floating-point types used.
Improving the Code
This code has no reason to use pow
; std::pow(i, 2)
should be i*i
. This results in exact arithmetic (up to the point of integer overflow) and completely avoids the question of whether pow
is correct.
Eliminating pow
leaves just sqrt
. If we know the implementation returns 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 only relies on sqrt
to return a result accurate within .5, which even a low-quality sqrt
implementation should provide for reasonable input values.