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?
@b3 has a great vectorization of rhs.
One typo though, needs to use times
and not mtimes
:
harmonicsum = cumsum(1 ./ (1:1e6));
rhs = harmonicsum + log(harmonicsum) .* exp(harmonicsum);
For lhs
, I propose the following, loosely based on Eratosthenes' Sieve:
lhs = 1 + [1:1e6];
lhs(1) = 1;
for iii = 2:numel(lhs)/2
lhs(2*iii:iii:end) = lhs(2*iii:iii:end) + iii;
end;
Execution time is just 2.45 seconds (for this half of the problem). Total including calculation of rhs
and find
is under 3 seconds.
I'm currently running the other version to make sure that the results are equal.
EDIT: found a bug with lhs(1)
and special-cased it (it is a special case, the only natural number where 1 and N aren't distinct factors)