I have a mistake in loops

Hello, I have somewhere a mistake that if N = 1000 the output misses some lines (don't know which), so I suppose there's a mistake somewhere in for loops. It works correctly with N = 50, 100, 500.
function [R, I] = problem2B(N)
I = 0;
for a = 3:N
for b = a:N
for c = b:N
if (a^2 + b^2) == c^2 && a+b+c < N
R(I+1, :) = [a+b+c, a, b, c];
I = I + 1;
elseif N < 12
R = zeros(4, 1);
end
end
end
end
if N <= 50
R = reshape(nonzeros(R), I, 4);
else
R = sortrows(R, 1);
end
end

3 Comments

What exactly do you mean when you say it misses rows?
[R I] = problem2B(100)
R = 17×4
12 3 4 5 24 6 8 10 30 5 12 13 36 9 12 15 40 8 15 17 48 12 16 20 56 7 24 25 60 10 24 26 60 15 20 25 70 20 21 29
I = 17
[R I] = problem2B(1000)
R = 324×4
12 3 4 5 24 6 8 10 30 5 12 13 36 9 12 15 40 8 15 17 48 12 16 20 56 7 24 25 60 10 24 26 60 15 20 25 70 20 21 29
I = 324
function [R, I] = problem2B(N)
I = 0;
for a = 3:N
for b = a:N
for c = b:N
if (a^2 + b^2) == c^2 && a+b+c < N
R(I+1, :) = [a+b+c, a, b, c];
I = I + 1;
elseif N < 12
R = zeros(4, 1);
end
end
end
end
if N <= 50
R = reshape(nonzeros(R), I, 4);
else
R = sortrows(R, 1);
end
end
sznailc
sznailc on 5 Nov 2021
Edited: sznailc on 5 Nov 2021
I have a test file that says, that not all possible pythagorean triples are displayed with N = 1000. Therefore I think there has to be a mistake with indexes that it skips some possible triples.
Note that if you change to
R = zeros(0,4);
then you can get rid of NONZEROS and RESHAPE.

Sign in to comment.

 Accepted Answer

Steven Lord
Steven Lord on 5 Nov 2021
Does your problem ask you to find all Pythagorean triples whose elements sum to less than 1000 or all whose elements sum to less than or equal to 1000?

1 Comment

wow, thank you, edited to a+b+c <= N. I couldn't tell what triple is missing and didn't know that it might be 1000

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2021a

Asked:

on 5 Nov 2021

Edited:

on 5 Nov 2021

Community Treasure Hunt

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

Start Hunting!