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

2 views (last 30 days)
Mairav Simon on 22 May 2020
Edited: John D'Errico on 22 May 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

Steven Lord on 22 May 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?

Mairav Simon on 22 May 2020
function output= findPyth(n)
for a=1:n;
for b=1:n;
for c=1:n;
a<=b<=c;
if c==sqrt(a.^2 +b.^2);
disp([a b c])
end
end
end
end
end
so now i have this, which works, but it gives me a lot of doubles. How do I tell the code I want [3 4 5] and [4 3 5] to be equal
Steven Lord on 22 May 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 on 22 May 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.