Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function called primes that takes two positive integers m and n as input

ID: 3934763 • Letter: W

Question

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

Explanation / Answer

% 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)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote