首页 > 代码库 > Pythagorean Triples CodeForces - 707C 推理题,大水题

Pythagorean Triples CodeForces - 707C 推理题,大水题

给定一个数n(1 <= n <= 1e9),判断这个数是否是一个直角三角形的边长,如果是,则输出另外两条边(1 <= x <= 1e18),否则输出-1.

参考题解:http://blog.csdn.net/harlow_cheng/article/details/69055614

首先,当n <= 2 的时候无解,其他时候都有解

假设n是直角边,a是斜边,则n^2 + b^2 = a^2;

n^2 = (a + b)*(a - b);

①假设n是偶数,则另(a - b) == 2;

==>  a + b = (n ^ 2) / 2;

==>  a* 2 = (n*n)/2 + 2;

==>  a = n*n/4 + 1;

因为n是大于二的偶数,所以a有整数解,b = a- 2;

 

②假设n是偶数,则另(a - b) == 1;

==>  a + b = (n ^ 2) ;

==>  a* 2 = (n*n) + 1;

因为n是大于二的奇数,所以a有整数解,b = a- 1;

代码如下

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main()
 4 {
 5     long long  x;
 6     cin >> x;
 7     if(x <= 2){cout<<"-1"<<endl; return 0;}
 8     if(x % 2)
 9     {
10         long long  a = (x * x + 1) / 2;
11         long long int b = a - 1;
12         cout << b << " " << a << endl;
13     }
14     else
15     {
16         long long int a = x * x / 4 + 1;
17         long long int b = a - 2;
18         cout << b << " " << a << endl;
19     }
20     return 0;
21 }

这是看完题解后补得题,惭愧,都说是大水题,还是没做出来,,,

看题的时候没法想到这方面,总是想着枚举暴力,懒,不愿动笔,这是一个大缺点,要改。!

 

Pythagorean Triples CodeForces - 707C 推理题,大水题