Optimizing MATLAB code

前端 未结 3 1269
慢半拍i
慢半拍i 2021-01-06 04:44

This code takes an extremely long time to run (more than 10 minutes). Is there any way in which I can optimize it so that it finishes in less than one minute?



        
3条回答
  •  生来不讨喜
    2021-01-06 04:59

    Vectorizing your algorithm where I could reduced the execution time slightly to ~8.5 minutes. Calculate all of the harmonic sums in one statement:

    harmonicsum = cumsum(1 ./ (1:1e6));
    

    You can now calculate the right-hand side in one statement:

    rhs = harmonicsum + log(harmonicsum) .* exp(harmonicsum);
    

    I couldn't vectorize the determination of the factors so this is the fastest way I could come up with to sum them. MATLAB's FACTOR command allows you to generate all the prime factors for each iteration. We then compute the unique set of products of all possible combinations using UNIQUE and NCHOOSEK. This avoids testing each integer as a factor.

    lhs = zeros(1e6, 1);
    for ii = 1:1e6
        primeFactor = factor(ii);
        numFactor = length(primeFactor);
        allFactor = [];
        for jj = 1:numFactor-1
           allFactor = [allFactor; unique(prod(nchoosek(primeFactor, jj), 2))];
        end
        lhs(ii) = sum(allFactor) + 1 + ii;
    end
    lhs(1) = 1;
    

    Find the indices at which the Riemann hypothesis is violated:

    isViolated = find(lhs > rhs);
    

提交回复
热议问题