Prime Numbers From List Function
Show older comments
I have to make a function that gives all the prime numbers from a list [2:N]
The following steps is what I came up with:
1. First we make a list of number from 2 to 10. We start with a tester equal to 2, and remove all multiples of 2 from the list.
2. We look at the next remaining value, which is 3. Our tester now becomes equal to
3. We again remove al multiples of 3 from the list. 3. Again, we look at the next remaining value. tester is now 5, we remove al multiples of 5 (of which there are none).
4. We do this one last time with 7, of which there are also no multiples.
5. The final list contains all primes up to 10.
10 should be variable N and the range of numbers should be equal to 2:N
Could someone help me how I put this in function form?
So that the function getPrimeNumbers(N) returns all the prime values from the list [2:N]
All help is greatly appreciated!
1 Comment
Walter Roberson
on 2 Dec 2019
Search for Eratosthenes in MATLAB Answers. You will find numerous implementations.
Answers (1)
Catalytic Kys
on 2 Dec 2019
0 votes
4 Comments
Steven Lord
on 2 Dec 2019
Since this sounds like a homework assignment, if it is show us the code you've written to try to solve the problem and ask a specific question about where you're having difficulty and we may be able to provide some guidance.
If you aren't sure where to start because you're not familiar with how to write MATLAB code, I suggest you start with the MATLAB Onramp tutorial (https://www.mathworks.com/support/learn-with-matlab-tutorials.html) to quickly learn the essentials of MATLAB.
If you aren't sure where to start because you're not familiar with the mathematics you'll need to solve the problem, I recommend asking your professor and/or teaching assistant for help.
If this is not a homework assignment, just use the primes function.
Catalytic Kys
on 2 Dec 2019
Steven Lord
on 2 Dec 2019
The primes function is implemented as a MATLAB function file (which is what I suspect you mean by "in code form".)
Walter Roberson
on 2 Dec 2019
That's odd. I just looked through https://www.mathworks.com/matlabcentral/answers/?term=tag%3A%22eratosthenes%22 and found full source code (and also a vectorized version.)
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!