I recently ran into a question on M.SE asking,
For positive integers x, y, z find a solution s.t. \$ \frac{x}{y+z} + \frac{y}{x+z} + \frac{z}{x+y} = 4 \$
so rather than think, I made a quick brute force c++ program to check for solutions:
unsigned lim = 251;
for(double x=1; x<lim; x++) {
for(double y=1; y<lim; y++) {
for(double z=1; z<lim; z++) {
printf("x=%.0f, y=%.0f, z=%.0f\n",x,y,z);
if( std::abs((x/(y+z) + y/(x+z) + z/(y+x)) - 4) <= 1E-15) {
printf("solution: x=%.0f, y=%.0f, z=%.0f\n",x,y,z);
}
}
}
}
All of this being within main
, of course. This is obviously slow so I was looking for optimizations. A couple of my thoughts were to remove the std::abs
call because the inside expression must be positive, perhaps I could simply check == 4
rather than account for precision. I couldn't figure out a way to drop a for
loop, because you can't isolate a variable. Otherwise I'm not sure what to do.
Questions:
- How can this code be sped up? My goal is
lim=1E3
in under a minute. As of now it takes31.0643 s
forlim=251
. - Can the for-loops be reduced? As of now formatting is not really an issue for me, but can this be simplified down to a single expression and/or loop? Or maybe look a little cleaner, without sacrificing optimization?
Update: After some research I'm now aware that the smallest known solution to this has numbers with 81 digits. I'm not concerned with this, just the above questions.