使用Matlab解决项目Euler#12

时间:2018-04-14 02:26:28

标签: algorithm matlab

我正在尝试使用Matlab解决项目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

1 个答案:

答案 0 :(得分:0)

这个技巧很简单,虽然它也困扰了我一段时间:你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