My professor assigned me to do the this homework with two numbers and writing a code that find which one is the prime for these two numbers

9 Ansichten (letzte 30 Tage)
Write a user-defined function that determines if a number is a prime number. Name the function pr=Trueprime(m), where the input arguments m is a positive integer and the output argument pr is 1 if m is a prime number and 0 if m is not a prime number. Do not use MATLAB’s built-in functions primes and isprime. If a negative number or a number that is not an integer is entered when the function is called, the error message “The input argument must be a positive integer.” is displayed.
(a) Use the function with 733, 2001, and 107.5
%%This is for one number
function pr=Trueprime(m)
if floor(m)~=m
disp('number is not a whole number')
else
for i=2:1:(m-1)
if rem(m,i)==0
disp('Number is not prime')
break
end
if i==(m-1)
disp('Number is prime')
end
end
end

Akzeptierte Antwort

David Fletcher
David Fletcher am 7 Apr. 2018
So what is the problem? The only obvious issue I see is that it doesn't check if the number is negative:
function pr=Trueprime(m)
if floor(m)~=m | m<=0
disp('The input must be a positive integer')
else
for i=2:1:(m-1)
if rem(m,i)==0
disp('Number is not prime')
break
end
if i==(m-1)
disp('Number is prime')
end
end
end
  2 Kommentare
Nezar Ayoub
Nezar Ayoub am 7 Apr. 2018
My question was if i have two numbers for example Trueprime([733 2001]). I am changing the question to two numbers instead of one number as in the question giving in the book part a, b and c Trueprime(733) Trueprime(2001) Trueprime(107.5)
David Fletcher
David Fletcher am 7 Apr. 2018
Bearbeitet: David Fletcher am 7 Apr. 2018
Probably a few ways you can go about it, but you've already written a function for single number prime, so make that a local function to a generalized Trueprime function that takes a vector argument like:
function pr=Trueprime(m)
result=zeros(1,length(m));
if any(floor(m)~=m) | any(m<0)
disp('The input must be a positive integer');
result=-1;
else
for iter=1:length(m)
result(iter)=privatePrime(m(iter));
end
end
pr=result;
end
function res=privatePrime(m)
pr=1
for i=2:1:(m-1)
if rem(m,i)==0
pr=0;
break
end
end
res=pr;
end
Trueprime([107 20 5 200 11])
ans =
1 0 1 0 1

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by