Pythagorean triples up to Z without loops
2 views (last 30 days)
Show older comments
I've been struggling with this problem for a while now and am looking for some insight.
The problem is in the form of a function: [A] = pyth(Z).
The problem is to find pythagorean triples where an output [A] is a [? x 3] matrix like:
a b c
3 4 5
6 8 10
5 12 13
where the highest value of c is a number Z.
The tricky part is not using loops.
I've been thinking of using meshgrid and reshape but can't quite put together how to use them. If anyone thinks of anything let me know! I'll be continuing to work on it in the meantime.
0 Comments
Accepted Answer
Roger Stafford
on 30 Apr 2017
Edited: Roger Stafford
on 30 Apr 2017
Instead of ‘meshgrid’ I would suggest using ‘ndgrid’:
[a,b,c] = ndgrid(1:Z);
A = [a(:),b(:),c(:)];
t = A(:,1).^2+A(:,2).^2==A(:,3).^2;
A = A(t,:);
Note: Using a well thought-out for-loop would probably be much faster and use less memory.
3 Comments
Roger Stafford
on 30 Apr 2017
Edited: Roger Stafford
on 30 Apr 2017
Just change t to:
t = A(:,1).^2+A(:,2).^2==A(:,3).^2 & A(:,1)<A(:,2);
Note: No pythagorean triple has A(:,1)==A(:,2), because sqrt(2) is irrational, so we haven't thrown out any valid triples here.
More Answers (0)
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!