Write a function that finds all the Three Pythagoras less than n?

3 ビュー (過去 30 日間)
Mairav Simon
Mairav Simon 2020 年 5 月 22 日
編集済み: John D'Errico 2020 年 5 月 22 日
function result = checkPyth(n)
y=n;
for i =1:1:length(y)
for j=1:1:length(y)
for k=1:1:length(y)
while (y(i)).^2+(y(j)).^2==(y(k)).^2
fprintf('true\n')
return
end
while (y(i)).^2+(y(j)).^2~=(y(k)).^2
fprintf('false\n')
return
end
end
end
end
This is the function I have so far, but it keeps returning false.
This function will first check if there exists numbers less than n such that i^2+j^2=k^2 with i,j,k<=n

回答 (1 件)

Steven Lord
Steven Lord 2020 年 5 月 22 日
Hint: how many times do these two loops run their loop bodies, and for which values?
y = 5;
disp('k1')
for k1 = 1:1:length(y)
disp(k1)
end
disp('k2')
for k2 = 1:1:y
disp(k2)
end
Do you want your loops to work like the k1 loop or the k2 loop?
  3 件のコメント
Steven Lord
Steven Lord 2020 年 5 月 22 日
Ideally you'd detect [3 4 5] when a = 3 and b = 4. So when a = 4, do you even want to check the case b = 3?
The "limits" of an inner loop variable can use the current value of an outer loop variable(s).
Z = zeros(5);
for row = 1:5
for col = row:5
Z(row, col) = 1;
end
end
disp(Z)
John D'Errico
John D'Errico 2020 年 5 月 22 日
編集済み: John D'Errico 2020 年 5 月 22 日
You can even go a little further, aince there are NO Pythagorean triples where a == b, since then a^2 + b^2 = 2*a^2, and we know that 2*a^2 can never be a perfect square itself. Essentially that just means there are no isosceles Pythagorean triangles. So the inner loop can start at row+1.
Disclaimer: I am a charter member of the group named SOCC: Save Our Cpu Cycles. I accept donations on behalf of the group, especially those paid in small unmarked bills.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeGlaciology についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by