项目euler 23 MATLAB

时间:2013-10-12 18:19:27

标签: matlab

我正在慢慢地按照项目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循环,代码很慢,所以我也在寻找更有效地解决这类问题的方法。

谢谢!

1 个答案:

答案 0 :(得分:1)

好吧,我没有足够的声誉来发表评论。你为什么要排除在自己身上添加相同的数字?问题陈述给出了示例12 + 12 = 24。

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