Matlab code to find all prime numbers between 2 and 5000

Thread Starter

Dapnc

Joined Feb 7, 2013
3
Need to write a matlab program that will find all prime numbers between 2 and 5000 but I can't use any built in matlab functions. Please help. It also has to run quickly.
 

tshuck

Joined Oct 18, 2012
3,534
Need to write a matlab program that will find all prime numbers between 2 and 5000 but I can't use any built in matlab functions. Please help. It also has to run quickly.
There are plenty of algorithms out there, what prevents you from using one of those? Or, are you wanting us to write the MATLAB code for you?

How quickly is quickly?
 

thatoneguy

Joined Feb 19, 2009
6,359
num = prime(5000)

Using that internal function, write the rest of the program, such as desired output format, optional input value for number (just like the built in function).

Once that is complete, Write a prime number algorithm. Run both prime(5000) and yourfunc(5000) to compare time to run, (remember to compile for max speed if you didn't know that). Once you get an algorithm that is close or less than the builtin function AND produces the same results, you are done.

That, combined with the algorithm link above should be all you need to get you started conceptually.
 

vortmax

Joined Oct 10, 2012
102
another good trick with matlab: many builtin functions are written in m-code, so you can see how they work by running `edit <fcn>`. However, the low level functions tend to be written in C, and so you can't see how they do their magic.
 

tgstanfi

Joined Feb 22, 2013
1
Hi! I am having to do this same project and I was just wondering if you ever figured out a code that worked? I have been working on it for hours now and I started one but it ran forever and isn't right. I would greatly appreciate it!
 

tshuck

Joined Oct 18, 2012
3,534
Hi! I am having to do this same project and I was just wondering if you ever figured out a code that worked? I have been working on it for hours now and I started one but it ran forever and isn't right. I would greatly appreciate it!
This site is not meant for sharing homework answers, it is, however, for educational purposes. If you'd like to start your own thread and post what you came up with, we'd be glad to take a look at it for you...
 

John_2016

Joined Nov 23, 2016
55
clear all;clc;close all
N=5e3
L=1:N;
tic
for k=1:1:numel(L)
L2{k}=[1:L(k)];
end
prime_list=[]
for k=1:1:N
if nnz(mod(k*ones(1,numel(L2{k})),L2{k}))==k-2
prime_list=[prime_list k];
end
end
toc

Elapsed time is 0.213874 seconds.


Following, a way to collect the result in text format:

prime_list_char=num2str(prime_list)
file_id=fopen('prime_list.txt','w');
fprintf(file_id,'Primes below %s :\n\n',num2str(N));
fprintf(file_id,'%s',prime_list_char);
fclose(file_id)
 
Top