Write a function called primes that takes two positive integers m and n as input
ID: 3931394 • 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
Code:
isPrime.m file
function val = isPrime(n)
factors = 0;
for i=1:n
if(eq(rem(n,i),0))
factors = factors + 1;
end
end
if(eq(factors,2))
val = 1;
else
val = 0;
end
end
primes.m file
function vec = primes(m,n)
vec = [];
for i=m:n
if eq(isPrime(i),1)
vec(end+1) = i;
end
end
end
test.m file
vec1 = primes(10,20)
vec2 = primes(20,50)
vec3 = primes(30,70)
Output:
vec1 =
11 13 17 19
vec2 =
23 29 31 37 41 43 47
vec3 =
31 37 41 43 47 53 59 61 67
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.