Writing a function to find prime numbers
Show older comments
This is homework. I already turned it in. I just don't know why this function doesn't work. I just want to learn what I missed. Thanks so much. This is the problem:
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.
Here is my code:
function result = myprime(n)
%%initially set output flag to true
result = true;
%%iterate over all positive integers 2,3,...,n-1
%%if n is not divisible by any of these factors....it is prime
if (n == 1)
result = 'false';
elseif (n == 2)
result = 'true';
else
for i=2:n-1,
if (mod(n,i)==0)
result = 'false';
end
end
end
%%return "true" or "false" instead of 1 or 0
if (result)
result = 'true';
else
result = 'false';
end
1 Comment
David Young
on 19 Aug 2015
Please format your code - it's not readable as you can see. (There's a "{} Code" button.)
Accepted Answer
More Answers (3)
Pranash Azrot
on 19 Aug 2015
%%Yaar meh edah kitaah see. meerah answer teek see. menu 100% meliah see. try karrey.
function x = myprime(n)
if (rem(n,2)~=0 || n==2)
k = fix(n/2);
else
x = false;
return;
end
for i = 1:k
w(i) = rem(n,i);
end
t=w(w==0);
[m n] = size(t);
if n<=1
x = true;
else
x = false;
return;
end
1 Comment
Daniel Kingsley
on 20 Aug 2015
Irfan Turk
on 21 Jul 2019
Edited: Irfan Turk
on 21 Jul 2019
You can find all prime numbers upto a certain number with the following code
%This code find all prime numbers
%upto the entered number
clear all;
N=input('Prime Numbers until:');
if N<2
return;
elseif N==2
disp(2);
return;
end
Pr(1)=2;Pr(2)=3;Count=3;
for i=4:N
C=Check(i);
if C==1
Pr(Count)=i;
Count = Count +1;
end
end
disp(Pr);
function C=Check(i)
C=1;
for k=2:(ceil(sqrt(i)))
if mod(i,k)==0
C=0;
end
end
end
3 Comments
John D'Errico
on 21 Jul 2019
How many times will you post this poor code to find prime numbers? I see that you have resurrected several old, long dead questions, only to post the same novice code.
Walter Roberson
on 21 Jul 2019
It would make more sense to break after assigning 0 to C.
Irfan Turk
on 22 Jul 2019
Thank you Walter. That's a good way to make the code better...
Farah Salman
on 27 Apr 2021
0 votes
function y = isPrime(N)
for i=2: floor(N/2)
if mod(N,i)==0
y=false;
return
end
y= true;
end
1 Comment
This code has at least one bug.
z = isPrime(2)
function y = isPrime(N)
for i=2:floor(N/2)
if mod(N,i)==0
y=false;
return
end
y= true;
end
end
Categories
Find more on MATLAB 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!