All possible pythagorean integer triplets x, y, z are given by the formulas:
x = k*(m*m - n*n),
y = k*(2*m*n),
z = k*(m*m + n*n)
where m > n > 0 and k are integer numbers. It's easy to verify that x*x + y*y = z*z for any selection of m > n > 0 and k integer numbers. So, the appropriate code to generate the triplets (x, y, z) is...a piece of cake.
in my above code if i change the type of k in line 20 from double to integer(also changing the function defination) then the program prints many wrong values along with the right ones..
the value of k is anyway a integer so how does changing the type matters??
> if i change the type of k in line 20 from double to integer
The floating point value (say 7.3) is narrowed to an int (7).
Avoid floating point for this; use integer operations.
A floating point value is an approximate representation a real number.
A value of an integral types is an exact representation of an integer (within a range).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
int main()
{
for( int i = 1; i < 100 ; ++i )
{
for( int j = i+1 ; j < 100 ; ++j )
{
int s = i*i + j*j ;
int k = j+1 ;
while( k*k < s ) ++k ;
if( k*k == s ) std::cout << i << ',' << j << ',' << k << '\n' ;
}
}
}
i didnt understand why type of k is changed in line 20 ??
is i change the type of k in my code then it prints wrong values why is that ??
while using double type it gives the right values ??
quite confusing
The Pythagorean triples by their nature are integer values, there shouldn't be any need to use type double unless the numbers are very large, in which case type longlong might be better. But int should be adequate here.
If your code prints the wrong values, then please show the code which is giving the problem.
And what (presumably incorrect) results did you get?
I took a look at this with a couple of different compilers, one of them given certain values seemed to have a small inaccuracy in the pow() function, which when truncating the result to an integer gave an incorrect value.
But without seeing the results, I don't know whether that's the issue here or not.