Pythagorean triples up to Z without loops

3 次查看(过去 30 天)
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.

采纳的回答

Roger Stafford
Roger Stafford 2017-4-30
编辑:Roger Stafford 2017-4-30
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 个评论
Roger Stafford
Roger Stafford 2017-4-30
编辑:Roger Stafford 2017-4-30
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.
Elena H.
Elena H. 2017-4-30
Thank you so much! I've been banging my head on a wall for hours.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by