Using pow(x,y) as a loop condition

I've written a bit of code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cmath>
#include <cstdio>
int main()
{
    for(int i=1; i<=1000; i++)
        for(int j=i+1; j<=1000; j++)
            for(int k=j+1; k<=1000; k++)
            {
                if(i+j+k==1000)
                {
                    if(pow(i,2) + pow(j,2) == pow(k,2)) //this doesnt work
                    //if(i*i + j*j == k*k) this works
                    {
                    std::cout << i << " " << j << " " << k << std::endl;
                    std::getchar();
                    }
                }
            }
    return 0;
}


Now I have absolutely no idea why does defining the if condition as if(pow(i,2) + pow(j,2) == pow(k,2)) doesnt work (ie. deosnt print anything) while defining it as if(i*i + j*j == k*k) works flawlessly - by working I mean printing out single set of 3 numbers.

Thanks in advance
Works for me and online compilers. For relatively small natural numbers there should not be representation issues and precision problems.

What compiler do you use?
GNU GCC, but i have no idea which version, as code::blocks doesnt display that..
You shouldn't use pow() to square numbers anyway. It's like using a sledgehammer to swat a fly.

if(i*i + j*j == k*k) is the better code, even if the pow() version was working.


The pow code likely isn't working because it's using the double version of the function, which means you'll have floating point precision errors.


MiiNiPaa wrote:
For relatively small natural numbers there should not be representation issues and precision problems.


I operate under the assumption that there's always the risk of precision problems with floating points.
Yeah, the problem with that code is that the meaning of pow(i,2) depends on the particular language version. int pow(int, int) was recently introduced, which is why it works for MiiNiPaa but not for you.
Topic archived. No new replies allowed.