Last active
April 11, 2019 15:12
-
-
Save avdotion/747c03bb0e72fe7553aaae8a8482d023 to your computer and use it in GitHub Desktop.
Sum of two squares (hypotenuse-method)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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