Compute the Maximum Integer Right Triangles Solutions
- 时间:2020-09-10 12:45:51
- 分类:网络文摘
- 阅读:136 次
If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.
{20,48,52}, {24,45,51}, {30,40,50}
For which value of p ≤ 1000, is the number of solutions maximised?
Maximum Integer Right Triangles Solutions
We can assume bruteforce the shorter side i from 1 to 1000. Then, we can bruteforce the the other side (of the right angle) from i to 1000 – i. The slope k can be computed via Sqrt(i*i+j*j). If three sides sum less or equal to 1000, then we increment the counter for the perimeter.
In the following Javascript, we use a dictionary (or hash map) to store the key-value pairs where key is the perimeter and the value is the number of the solutions when corresponding perimeter is chosen.
And at the end, we have to go through the dictionary to find out the key where the maximum value is stored.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | let count = { }; for (let i = 1; i <= 1000; ++ i) { for (let j = i; i + j <= 1000; ++ j) { let k = Math.floor(Math.sqrt(j * j + i * i)); if (k * k == i * i + j * j) { let p = i + j + k; if (p <= 1000) { if (typeof count[p] === 'undefined') { count[p] = 1; } else { count[p] ++; } } } } } const keys = Object.keys(count); let cnt = 0; let p = 0; for (let key of keys) { if (count[key] > cnt) { cnt = count[key]; p = key; } } console.log(p); |
let count = {
};
for (let i = 1; i <= 1000; ++ i) {
for (let j = i; i + j <= 1000; ++ j) {
let k = Math.floor(Math.sqrt(j * j + i * i));
if (k * k == i * i + j * j) {
let p = i + j + k;
if (p <= 1000) {
if (typeof count[p] === 'undefined') {
count[p] = 1;
} else {
count[p] ++;
}
}
}
}
}
const keys = Object.keys(count);
let cnt = 0;
let p = 0;
for (let key of keys) {
if (count[key] > cnt) {
cnt = count[key];
p = key;
}
}
console.log(p);–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:柚子营养价值高多吃对健康大有益处 美食“扬州炒饭”新标准公布了制作方法 推荐5大养胃食物帮助呵护你的“胃” 红薯营养丰富但空腹吃红薯需要谨慎 香蕉不能和哪些食物一起食用呢? 男性多吃香蕉有助于性功能疾病的康复 权威发布:常见的致癌食物你吃过几种 “最大份扬州炒饭”喂猪背后的浮躁心态 吉尼斯宣布“最大份扬州炒饭”纪录无效 包菜有意想不到的防癌养胃保健功效
- 评论列表
-
- 添加评论