Write a function called primes that takes two positive integ

Write a function called primes that takes two positive integers m and n as input arguments, and returns vector containing all the prime numbers between m and n. If m > n, then an empty vector is returned. (A number is called a prime number if it is only divisible by 1 and by itself.)

The function will be invoked as follows:

vec = primes(m, n);

Following is an example of correct function behavior:

>> n_vec = primes(10, 20)

n_vec = 11 13 17 19

>> n_vec = primes(20, 50)

n_vec = 23 29 31 37 41 43 47

Do not use MATLAB’s built-in function isprime

Solution

% matlab code determine prime numbers in range

function n_vec = primes(m,n)
i = 1;
if m > n
n_vec = [];
else
for N=m:n
prime = true;
for f = 2:ceil(sqrt(N))
if mod(N,f) == 0
prime = false;
break;
end
end
if prime == true
n_vec(i) = N;
i = i + 1;
end
end
end
end

n_vec = primes(10, 20);
disp(n_vec);
% output: 11 13 17 19
n_vec = primes(20, 50);
disp(n_vec);
% output: 23 29 31 37 41 43 47
n_vec = primes(10, 9);
disp(n_vec);
% output: [](0x0)

Write a function called primes that takes two positive integers m and n as input arguments, and returns vector containing all the prime numbers between m and n.

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site