鱼C论坛

 找回密码
 立即注册
查看: 4543|回复: 17

题目37:找出所有11个可以双向裁剪的质数的和

[复制链接]
发表于 2017-6-14 22:51:23 | 显示全部楼层
此代码使用matlab编程
Problem37所用时间为: 14.9352秒
Problem37的答案为: 748317
  1. %% Problem37.m
  2. % 最后编辑时间:17-06-14 22:34
  3. % 找出11个双向裁剪质数的和
  4. % Problem37所用时间为: 14.9352秒
  5. % Problem37的答案为: 748317
  6. function Output = Problem37()
  7. tic
  8. Limit = 1000000;
  9. Vector = GetPrime(Limit);
  10. Vector = Vector(5:end);
  11. N = length(Vector);

  12. Output = 0;

  13. Time = 0;

  14. for ii = 1:N
  15.     Judge = 1;
  16.     L = length(num2str(Vector(ii)));
  17.     for jj = 1:L-1
  18.         if isprime(floor(Vector(ii)/(10^jj))) == 0
  19.             Judge = 0;
  20.             break
  21.         end
  22.     end
  23.    
  24.     if Judge == 1
  25.         Str = num2str(Vector(ii));
  26.         for jj = 2:L
  27.             if isprime(str2double(Str(jj:L))) == 0
  28.                Judge = 0;
  29.                break
  30.             end
  31.         end
  32.     end
  33.    
  34.     if Judge == 1
  35.         Output = Output + Vector(ii);
  36.         Time = Time + 1;
  37.         disp(Vector(ii))
  38.         if Time == 11
  39.             break
  40.         end        
  41.     end
  42.          
  43. end

  44. toc
  45. disp('此代码使用matlab编程')
  46. disp(['Problem37所用时间为: ',num2str(toc),'秒'])
  47. disp(['Problem37的答案为: ',num2str(Output)])
  48. end
  49. %% 得到n以下的所有质数
  50. function Vector = GetPrime(n)
  51. if nargin == 0
  52. n = 10000;
  53. end

  54. Judge = ones(1,n-1);
  55. Judge(1) = 0;
  56. for ii = 1:n-1
  57.     if Judge(ii) == 1
  58.         for jj = 2*ii : ii : n-1
  59.             Judge(jj) = 0;
  60.         end
  61.     end
  62. end
  63. Vector = find(Judge == 1);
  64. end
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-9 03:03

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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