0

我一直在尝试使用 Mathematica 中的 Do 和 If 语句找到毕达哥拉斯三元组。

我需要测试两个整数 (a,b) 是否构造一个毕达哥拉斯三元组,其中:1 <= a <= 100 && 1<= b <= 100

If[Element[Sqrt[a^2 + b^2], Integers] && a < b && 
  b < Sqrt[a^2 + b^2], 
 Print["(", a, ",", b, ",", Sqrt[a^2 + b^2] ")"]]

该片段给出了打印的三元组,它们实际上是一个毕达哥拉斯三元组,但我不确定如何测试 a 和 b 的所有值。任何帮助将不胜感激。

4

1 回答 1

0
Do[ If[ IntegerQ[r = Sqrt[i^2 + j^2]], Print[{i, j, r}]], {i, 
  100}, {j, i - 1}]

可能最好保存结果而不是使用Print

Reap[Do[ If[ IntegerQ[r = Sqrt[i^2 + j^2]], Sow[{i, j, r}]], {i, 
    100}, {j, i - 1}]][[2, 1]] 

另一种方式..

Cases[Append[#, Norm@#] & /@ 
  Subsets[Range[100], {2}], {_, _, _Integer}]

{{3, 4, 5}, {5, 12, 13}, {6, 8, 10}, {7, 24, 25}, {8, 15, 17}, {9, 12, 15}, { 9, 40, 41}, {10, 24, 26}, {11, 60, 61}, {12, 16, 20}, {12, 35, 37}, {13, 84, 85}, {14, 48, 50}, {15, 20, 25}, {15, 36, 39}, {16, 30, 34}, {16, 63, 65}, {18, 24, 30}, {18, 80, 82}, {20, 21, 29}, {20, 48, 52}, {20, 99, 101}, {21, 28, 35}, {21, 72, 75}, {24, 32, 40} , {24, 45, 51}, {24, 70, 74}, {25, 60, 65}, {27, 36, 45}, {28, 45, 53}, {28, 96, 100}, { 30, 40, 50}, {30, 72, 78}, {32, 60, 68}, {33, 44, 55}, {33, 56, 65}, {35, 84, 91}, {36, 48, 60}, {36, 77, 85}, {39, 52, 65}, {39, 80, 89}, {40, 42, 58}, {40, 75, 85}, {40, 96, 104}, {42, 56, 70}, {45, 60, 75}, {48, 55, 73}, {48, 64, 80}, {48, 90, 102}, {51, 68, 85} , {54, 72, 90}, {56, 90, 106}, {57, 76, 95}, {60, 63, 87}, {60, 80, 100}, {60, 91, 109}, { 63, 84, 105},{65, 72, 97}, {66, 88, 110}, {69, 92, 115}, {72, 96, 120}, {75, 100, 125}, {80, 84, 116}}

Do如果您需要运行到非常大的n地方,这实际上会更好,这Subsets会消耗大量内存。

于 2017-02-16T15:03:25.303 回答