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

3 Ansichten (letzte 30 Tage)
Mairav Simon
Mairav Simon am 22 Mai 2020
Bearbeitet: John D'Errico am 22 Mai 2020
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

Antworten (1)

Steven Lord
Steven Lord am 22 Mai 2020
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 Kommentare
Steven Lord
Steven Lord am 22 Mai 2020
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 am 22 Mai 2020
Bearbeitet: John D'Errico am 22 Mai 2020
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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Glaciology finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by