【问题标题】:Solving Project Euler #12 with Matlab用 Matlab 求解 Project Euler #12
【发布时间】:2018-04-14 02:26:27
【问题描述】:

我正在尝试用 Matlab 解决 Project Euler 的问题 #12,这就是我想出的找到给定数字的除数的方法:

function [Divisors] = ND(n)
p = primes(n); %returns a row vector containing all the prime numbers less than or equal to n
i = 1;
count = 0;
Divisors = 1;

  while n ~= 1
      while rem(n, p(i)) == 0 %rem(a, b) returns the remainder after division of a by b
          count = count + 1;
          n = n / p(i);
      end
      Divisors = Divisors * (count + 1);
      i = i + 1;
      count = 0;
  end

end

在此之后,我创建了一个函数来评估产品n * (n + 1) / 2 的除数以及该产品何时达到特定限制:

function [solution] = Solution(limit)
n = 1;
product = 0;

  while(product < limit)
     if rem(n, 2) == 0
         product = ND(n / 2) * ND(n + 1);
     else
         product = ND(n) * ND((n + 1) / 2);
     end
     n = n + 1;
  end

  solution = n * (n + 1) / 2;

end

我已经知道答案,这不是函数Solution 的返回值。有人可以帮我找出编码的问题。

当我运行Solution(500)(500 是问题中指定的限制)时,我得到76588876,但正确答案应该是:

76576500.

【问题讨论】:

    标签: algorithm matlab


    【解决方案1】:

    诀窍很简单,但也困扰了我一段时间:while 循环中的迭代放错了位置,这将导致解决方案比真实答案大一点。

    function [solution] = Solution(limit)
    n = 1;
    product = 0;
    
      while(product < limit)
         n = n + 1;     %%%But Here
         if rem(n, 2) == 0
             product = ND(n / 2) * ND(n + 1);
         else
             product = ND(n) * ND((n + 1) / 2);
         end
         %n = n + 1;    %%%Not Here
      end
    
      solution = n * (n + 1) / 2;
    
    end
    

    Matlab 2015b 的输出:

    >> Solution(500)
    
    ans =
    
        76576500
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      相关资源
      最近更新 更多