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.
0 个评论
采纳的回答
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
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!