How to make a program to check if a number is a prime?

조회 수: 55 (최근 30일)
Marin
Marin 2013년 5월 14일
댓글: Walter Roberson 2021년 1월 20일
Hello I'm just starting with matlab and I have to make a program to check if a number is a prime. My pgrogramme looks like that but it ain't working.
function prime(x)
i= 3:2:sqrt(x) ;
if mod(x,2) == 0
disp ('is not a prime')
if mod(x,i) > 0
disp('is not a prime')
else
disp ('is a prime')
end
end
Can you help me make my code work please.
  댓글 수: 1
Waseem Wasi
Waseem Wasi 2019년 5월 25일

First condition is true but in second you to have write if(mod(x,2)==1) then this will be show a prime number

댓글을 달려면 로그인하십시오.

답변 (3개)

Sean de Wolski
Sean de Wolski 2013년 5월 14일
  댓글 수: 2
Marin
Marin 2013년 5월 14일
I know there's a program to do that, I have to make my own...
Jan
Jan 2013년 5월 14일
@Marin: It is useful to mention such important details in the question already. Otherwise the forum users waste the time for mentioning the built-in functions.

댓글을 달려면 로그인하십시오.


Jan
Jan 2013년 5월 14일
Do you see the difference between:
if mod(x,2) == 0
disp ('is not a prime')
and
if mod(x,i) > 0
disp ('is not a prime')
In the first test you check, if the modulo returns 0. In the second, you want the result to be non-zero to decide, that x is not a prime. Suspicious.
Then the variable i is a vector. In consequence mod(x, i) replies a vector also. But the if-condition must be a scalar, as the English term "if" implies more or less. The functions all() and any() are useful in such cases.
You find a lot of useful links, when you search in the net for prime number algorithms. E.g. ask WikiPedia for Eratosthenes.

Anmol  singh
Anmol singh 2021년 1월 20일
Prime number - a number can devide by itself or 1 so now we can iterate loop 2 to n/2 , if n is devide by any number from 2 to n/2 then it is not prime .
loop : i = 2 <= n/2
if mod(n/i == 0)
disp ('is not a prime');
return ;
end if
i++;
end loop
disp ('it is a prime');
return ;
It is very nice trick to check prime number till n/2 .Not need to iterate 2 to n-1
Refrence :
  댓글 수: 1
Walter Roberson
Walter Roberson 2021년 1월 20일
That is not MATLAB code. It is also not C or C++ code. I do not know what programming language it is. Certainly not java as might be hinted by the link to a java blog.
There is no need to iterate to n/2: you can stop iterating at floor(sqrt(n))

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by