Skip to content

Instantly share code, notes, and snippets.

@avdotion
Last active April 11, 2019 15:12
Show Gist options
  • Save avdotion/747c03bb0e72fe7553aaae8a8482d023 to your computer and use it in GitHub Desktop.
Save avdotion/747c03bb0e72fe7553aaae8a8482d023 to your computer and use it in GitHub Desktop.
Sum of two squares (hypotenuse-method)
#include <iostream>
int sqr(int n) {
return n * n;
}
int main() {
int r{};
std::cin >> r;
int x{};
int y{};
for (x = 0; sqr(x - 1) <= r; ++x) {}
while (y <= x) {
if (abs(r - sqr(x - 1) - sqr(y)) < abs(r - sqr(x + 1) - sqr(y)) &&
abs(r - sqr(x - 1) - sqr(y)) < abs(r - sqr(x) - sqr(y + 1))) {
x -= 1;
} else if (abs(r - sqr(x + 1) - sqr(y)) < abs(r - sqr(x - 1) - sqr(y)) &&
abs(r - sqr(x + 1) - sqr(y)) < abs(r - sqr(x) - sqr(y + 1))) {
x += 1;
} else {
y += 1;
}
if ((sqr(x) + sqr(y)) == r && x * y != 0) {
std::cout << x << " " << y << std::endl;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment