16 Jul 2011

Euler Project10 欧拉工程10




The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.

10以内的素数之和为2+3+5+7 = 17
计算2,000,000(两百万)以内的素数之和.
此题的要快速需要用素数筛生成素数列表,然后求和即可.
好在matlab提供了primes函数,因此可以大大省事.下面注释掉的代码使用的是循环+判断.
时间差别是巨大的: 45s对0.08s. %% Find the sum of all the primes below two million.
% ========use loop================
% Elapsed time is 45.486655 seconds.
% ans =
% 142913828922
% ========use primes=============
% Elapsed time is 0.087248 seconds.
% ans =
% 142913828922
function result = euler10()
tic;
result = sum(primes(2000000));
% a = 2:2000000;
% b = isprime(a);
% result = sum(a(b));
toc;
end

No comments :

Post a Comment