The following is Problem 10 from Project Euler. As of this posting, it has been solved 62,312 times.
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
MATLAB and Octave have a function called “primes” which takes any number as an argument and returns an array of all the prime numbers below that number.
For example, calling primes(10) would return an array of [2 3 5 7].
So solving this problem in MATLAB feels like cheating. The below code executed in just a few milliseconds.
% ProjectEuler.net problem #010 % The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. % Find the sum of all the primes below two million. tic(); format long final_answer = sum(primes(2e6)) exec_time = toc()
I suppose I could write an algorithm to find the primes and brute-force it with an IF or WHILE loop, but I think I’d rather move on to the next problem. So there you have it. Happy coding!