how to make a function that take an integer as input and return ture if this prime otherwise false
Show older comments
Hi everyone; I am going to attempt that question: Write a function myprime that takes n, a positive integer, as an input and returns true if n is prime or returns false otherwise. Do not use the isprime or primes or factor built-‐in functions. Hint: you can use the rem or fix functions. I am using that code
function prime=myprime(n)
a=abs(n);
i=1;
while i<a
if rem(a,i)~=0
prime='TURE';
else
prime='FALSE';
end
i=i+1;
end
end
and getting error
Feedback: Your function made an error for argument(s) 2
Your solution is _not_ correct.
Guide me where i need corrections in my code. Thanks in advance for assistance..
3 Comments
B.k Sumedha
on 28 May 2015
Y cant u try with isprime() function in matlab
Muhammad Usman Saleem
on 28 May 2015
Ryan Livingston
on 28 May 2015
I removed the product tag for "MATLAB Coder" below since this example is not using the product MATLAB Coder. Please only use that product tag when this product is involved. Thank you.
Accepted Answer
More Answers (2)
B.k Sumedha
on 28 May 2015
function result = isprime2(number)
number=5;
result=true;
%%check if number is a nonnegative integer
if floor(number)~=number || number<0
result=false;
return
end
%%check if number can be divided by another integer
for k=2:(number/2)
if rem(number,k)==0
result=false;
return
end
end
Returns 1 if the number isprime and returns 0 if the number is not prime.
1 Comment
Muhammad Usman Saleem
on 28 May 2015
charu sharma
on 20 Aug 2015
0 votes
For number n being prime, if it is divisible by any of the numbers from 2 to n/2 then it is not prime so you just need to check the divisibility till n/2. MATLAB uses 0 or 1 in place of false and true. You can refer this too for less time complexity: http://farzicoders.blogspot.in/2015/08/write-function-myprime-that-takes-n.html
Categories
Find more on Performance and Memory in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!