一、问题描述
二、问题分析
基本的暴力思路比较简单,同时书中还提到了满足这样条件的解法刚好就是一组满足勾股定理的平方数,在代码实现的时候用缩小了搜索范围。
在解决问题的思考中,曾想过将一组勾股平方数的斜边记录下来以作解法模式,遇到其倍数的时候就直接跳过而不进行搜索,但是最后发现在斜边相同的情况下,有些数可以有两种组合方式,例如(36,77,85)和(13,84,85)。于是最后还是使用书中两条直角边互质的方式来判断是否是相同解法模式。
对于这个问题可以参考这里:是否存在正整数a,b,c满足a²+b²=c²,当给定一个c值时,a,b有多种取值? - 知乎 (zhihu.com)
三、代码实现
1.C/C++实现
#include <iostream>
using namespace std;
int gcd(int a, int b) {
return b > 0 ? gcd(b, a % b) : a;
}
pair<bool, int> getSqrt(int n)
{
int tmp = ceil(sqrt(n));
if (tmp * tmp == n)
return make_pair(true, tmp);
return make_pair(false, -1);
}
int main()
{
double sqrtTwo = sqrt(2);
int count = 0;
for (int i = 1; i <= 500 / 4; i++)
for (int j = 1; j < ceil(i / sqrtTwo); j++)
{
pair<bool, int> tmp = getSqrt(i * i - j * j);
if (tmp.first && gcd(tmp.second, j) == 1)
count++;
}
cout << count << endl;
}
2.Python实现
# coding=utf-8
import math
def get_sqrt(n):
tmp = math.ceil(math.sqrt(n))
if tmp ** 2 != n:
return -1, False
return tmp, True
if __name__ == '__main__':
count = 0
sqrtTwo = math.sqrt(2)
for i in range(1, 500 // 4 + 1):
for j in range(1, math.ceil(i / sqrtTwo)):
value, flag = get_sqrt(i ** 2 - j ** 2)
if flag is True and math.gcd(j, value) == 1:
count += 1
print(count)