how do i determine the output of how many prime numbers are there and list them by the function that i created?

2 views (last 30 days)
I have created my own function(without using isprime or any other built in functions) to determine whether an integer is a prime number or not. But I need to call the function that I created and input a range of numbers [10 20] and the output should be there are 4 prime numbers btwn 10 and 20 which are 11 13 17 19. I have attached the function that I have created. Thanks I am new to matlab.

Accepted Answer

Geoff Hayes
Geoff Hayes on 28 Nov 2015
Rather than have your function MyPrime output strings indicating whether the number is prime or not, consider changing the outputs to a zero (false or not prime) or (true or prime). With the boolean output, you can more easily determine which numbers (from your array) are prime or not. Suppose that MyPrime returns a zero or one, and consider the following
myIntegers = 10:20; % create a list of integers between 10 and 20
You can use the arrayfun to apply your MyPrime function to each integer with the output being an array of ones and zeros.
primeOrNot = arrayfun(@(k)MyPrime(k),myIntegers);
If element k of primeOrNot is a one, then you know that the kth element of myIntegers is a prime. To extract these numbers just do
myIntegers(logical(primeOrNot))
which gives us an answer of
ans =
11 13 17 19
Note that the cast of primeOrNot as logical is necessary to access the elements of myIntegers. You can avoid this cast if your output from MyPrime is true or false rather than 1 or zero respectively.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!