The following is problem 7 of Project Euler. As of this posting, it has been solved 74,865 times.
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?
As MATLAB and Octave already have an optimized function for returning prime numbers, this simple solution almost feels like cheating. Maybe I’ll go back later and try a brute force approach with a couple of loops. Or maybe I’ll just live with the below and move on to the next one.
% ProjectEuler.net problem #007 % By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we % can see that the 6th prime is 13. % What is the 10,001st prime number? % answer should be 104,743, exec time 0.01036. clear tic(); which_prime = 10001; % This is the prime we're looking for. % We can start our counter pretty high since we know % that there are not 10k prime numbers below 100,000. a = 100000; while length(primes(a)) < which_prime a = a + 10000; end get_primes = primes(a); final_answer = get_primes(which_prime)' exec_time = toc()
You could easily do this with one line of code and it would still execute in about a tenth of a second. You’d just have to guess the upper limit. Maybe guess that there are at least 10,000 prime numbers below, say 2 million, and you could execute the following line:
a = primes(2e6)(10001)
There you have it. Happy coding!