【问题标题】:project euler 23 MATLAB项目欧拉 23 MATLAB
【发布时间】:2013-10-12 18:19:26
【问题描述】:

我正在慢慢地解决 Euler 项目中的问题 23,但我遇到了障碍。问题 #23 涉及尝试找到不能由两个丰富的数字创建的所有数字的总和。

首先是我的代码:

function [divisors] = SOEdivisors(num)
%SOEDIVISORS This function finds the proper divisors of a number using the sieve
%of eratosthenes


%check for primality
if isprime(num) == 1
    divisors = [1];


%if not prime find divisors
else
    divisors = [0 2:num/2]; %hard code a zero at one.

    for i = 2:num/2
        if divisors(i) %if divisors i ~= 0

            %if the remainder is not zero it is not a divisor
            if rem(num, divisors(i)) ~= 0

                %remove that number and all its multiples from the list
                divisors(i:i:fix(num/2)) = 0;
            end
        end
    end

    %add 1 back and remove all zeros
    divisors(1) = 1;
    divisors = divisors(divisors ~= 0);
end
end

这个函数找到丰富的数字

function [abundantvecfinal] = abundantnum(limitnum)
%ABUNDANTNUM creates a vector of abundant numbers up to a limit.


abundantvec = [];

%abundant number count
count = 1;

%test for abundance
for i = 1:limitnum

    %find divisors
    divisors = SOEdivisors(i);

    %if sum of divisors is greater than number it is abundant, add it to
    %vector
    if i < sum(divisors)
        abundantvec(count) = i;
        count = count + 1;
    end


end

abundantvecfinal = abundantvec;
end

这是主脚本

%This finds the sum of all numbers that cannot be written as the sum of two
%abundant numbers and under 28123

%get abundant numbers
abundant = abundantnum(28153);

%total non abundant numbers
total = 0;

%sums
sums = [];

%count moves through the newsums vector allowing for a new space for each
%new sum
count = 1;

%get complete list of possible sums under using abundant numbers under
%28123 then store them in a vector
for i = 1:length(abundant)
    for x = 1:length(abundant)

        %make sure it is not the same number being added to itself
        if i ~= x
            sums(count) = abundant(i) + abundant(x);
            count = count + 1;
        end
    end
end

%setdiff function compares two vectors and removes all similar elements
total = sum(setdiff(1:28153, sums));


disp(total)

第一个问题是它给了我错误的答案。我知道我得到了正确的正确除数和正确的丰富数字,所以问题可能出在主脚本上。似乎它几乎可以肯定地在于创造巨额资金。我希望有人能够找到我无法找到的错误。

除此之外,由于多个 for 循环,代码很慢,所以我也在寻找更有效地解决此类问题的方法。

谢谢!

【问题讨论】:

    标签: matlab


    【解决方案1】:

    好吧,我没有足够的声誉来发表评论。您为什么要排除将相同的数字添加到自身?问题陈述给出的例子是 12+12=24。

    我也看不出 x 应该小于 i 的原因。您不需要将相同的两个数字相加两次。

    【讨论】:

    • 老实说,我不知道为什么要阻止添加两个相同的丰富数字。我想我假设他们想要两个不同的丰富数字的总和。无论如何,所以脚本现在可以工作了。有什么效率方面的建议吗?就目前而言,脚本运行需要 46 秒。
    • 好吧,正如我所说,您的 for 循环 for x 可能应该从 i 到末尾,而不是从 1 开始,否则您将每对丰富的数字添加两次。这种技术一直在出现。除此之外,您现在可以访问论坛,因此那里有各种效率提示。我简化它的方法是将所有整数添加到 28000 或使用三角数公式,然后保留一个相同大小的 bool 数组,指示哪些数字已经通过总和获得,每次我得到一个新的总和时,我将从总数中减去。
    • 现在请删除您的代码,以免在 PE 上为其他人毁了它
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    相关资源
    最近更新 更多