找回密码
 注册
Simdroid-非首页
查看: 91|回复: 1

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

[复制链接]
发表于 2010-9-27 10:16:21 | 显示全部楼层 |阅读模式 来自 北京
本帖最后由 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的数字中求出可以写为最多组勾股数之和的数。

  1. clear;clc;close all;
  2. t=1;
  3. for i=1:500
  4.     for j=i:1000
  5.         for k=j:1000
  6.             if i^2+j^2==k^2&&i+j+k<=1000
  7.                 a(t,:)=[i,j,k];
  8.                 t=t+1;
  9.             end
  10.         end
  11.     end
  12. end
  13. [m,n]=mode(sum(a,2))
  14. [code]Elapsed time is 36.998713 seconds.
复制代码

[/code]以上是我的方法,效率不高,还有其他的好的办法么,请多指导!

评分

1

查看全部评分

发表于 2010-9-27 10:31:18 | 显示全部楼层 来自 河北廊坊
Simdroid开发平台
我把我的做法再写一遍
  1. clear;clc;close all
  2. tic;
  3. [a,b]=meshgrid(1:500);
  4. c=a.^2+b.^2;
  5. d=sqrt(c);
  6. f=round(d);
  7. e=f==d;
  8. k=find(e);
  9. p=a(e)+b(e)+f(e);
  10. q=accumarray(p,1);
  11. m=find(q==max(q))
  12. ij=find(p==m);
  13. re=[a(k(ij)) b(k(ij)) f(k(ij))];
  14. re=unique(sort(re,2),'rows');
  15. fprintf('%d^2+%d^2=%d^2\n',re');
  16. toc
复制代码
  1. 40^2+399^2=401^2
  2. 56^2+390^2=394^2
  3. 105^2+360^2=375^2
  4. 120^2+350^2=370^2
  5. 140^2+336^2=364^2
  6. 168^2+315^2=357^2
  7. 210^2+280^2=350^2
  8. 240^2+252^2=348^2
  9. Elapsed time is 0.030733 seconds.
复制代码
如果借鉴ls的mode函数
代码改进为:
  1. tic;
  2. [a,b]=meshgrid(1:500);
  3. c=a.^2+b.^2;
  4. d=sqrt(c);
  5. f=round(d);
  6. e=f==d;
  7. k=find(e);
  8. p=a(e)+b(e)+f(e);
  9. m=mode(p);
  10. ij=find(p==m);
  11. re=[a(k(ij)) b(k(ij)) f(k(ij))];
  12. re=unique(sort(re,2),'rows');
  13. fprintf('%d^2+%d^2=%d^2\n',re');
  14. toc
复制代码
  1. 40^2+399^2=401^2
  2. 56^2+390^2=394^2
  3. 105^2+360^2=375^2
  4. 120^2+350^2=370^2
  5. 140^2+336^2=364^2
  6. 168^2+315^2=357^2
  7. 210^2+280^2=350^2
  8. 240^2+252^2=348^2
  9. Elapsed time is 0.023293 seconds.
复制代码

评分

1

查看全部评分

回复 不支持

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Simapps系列直播

Archiver|小黑屋|联系我们|仿真互动网 ( 京ICP备15048925号-7 )

GMT+8, 2024-9-23 12:30 , Processed in 0.043007 second(s), 18 queries , Gzip On, MemCache On.

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表