upc1984 发表于 2010-9-27 10:16:21

[欧拉习题] ProjEuler[39]:找勾股数

本帖最后由 upc1984 于 2010-9-27 10:28 编辑

原帖http://forum.simwe.com/thread-911102-1-1.htmlMathematica 解法用matlab实现
If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.

{20,48,52}, {24,45,51}, {30,40,50}

For which value of p ≤ 1000, is the number of solutions maximised?

120可以写为三组勾股数(整数)之和,分别是{20,48,52}, {24,45,51}, {30,40,50}。要求在不超过1000的数字中求出可以写为最多组勾股数之和的数。
clear;clc;close all;
t=1;
for i=1:500
    for j=i:1000
      for k=j:1000
            if i^2+j^2==k^2&&i+j+k<=1000
                a(t,:)=;
                t=t+1;
            end
      end
    end
end
=mode(sum(a,2))
Elapsed time is 36.998713 seconds.
以上是我的方法,效率不高,还有其他的好的办法么,请多指导!

qibbxxt 发表于 2010-9-27 10:31:18

我把我的做法再写一遍clear;clc;close all
tic;
=meshgrid(1:500);
c=a.^2+b.^2;
d=sqrt(c);
f=round(d);
e=f==d;
k=find(e);
p=a(e)+b(e)+f(e);
q=accumarray(p,1);
m=find(q==max(q))
ij=find(p==m);
re=;
re=unique(sort(re,2),'rows');
fprintf('%d^2+%d^2=%d^2\n',re');
toc40^2+399^2=401^2
56^2+390^2=394^2
105^2+360^2=375^2
120^2+350^2=370^2
140^2+336^2=364^2
168^2+315^2=357^2
210^2+280^2=350^2
240^2+252^2=348^2
Elapsed time is 0.030733 seconds.如果借鉴ls的mode函数
代码改进为:tic;
=meshgrid(1:500);
c=a.^2+b.^2;
d=sqrt(c);
f=round(d);
e=f==d;
k=find(e);
p=a(e)+b(e)+f(e);
m=mode(p);
ij=find(p==m);
re=;
re=unique(sort(re,2),'rows');
fprintf('%d^2+%d^2=%d^2\n',re');
toc40^2+399^2=401^2
56^2+390^2=394^2
105^2+360^2=375^2
120^2+350^2=370^2
140^2+336^2=364^2
168^2+315^2=357^2
210^2+280^2=350^2
240^2+252^2=348^2
Elapsed time is 0.023293 seconds.
页: [1]
查看完整版本: [欧拉习题] ProjEuler[39]:找勾股数