フィルターのクリア

how to use conditional statement realizing prime function

5 ビュー (過去 30 日間)
Shuoze Xu
Shuoze Xu 2022 年 6 月 17 日
コメント済み: Walter Roberson 2022 年 6 月 19 日
Hi.
I want to use code to check if a number isprime. I know isprime () but I don't want to use it because I want to know how to use judgments to do tha.
Here is my code.
%function code
function[a,b] = isPrime(n)
% A number, n, is not prime if any number between 2 and n/2 divides the number without any remainder.
a = 1; % a = 1 means true
b = 0; % b = 0 means false
half = n/2; % get the half nums of n
for i = 2:half
if(mod(n,i)~=0) % if there is remainder
continue; % keep check
elseif(mod(n,i) == 0)
disp(b); % display false
break; % stop loop
end
disp(a);
end
end
% driver code
n = 9;
[x1,x2]= isPrime(n);
disp(isPrime(n));
Sample test:
isPrimedriver
0
0
1
It should output zero and stop looping, why it work twice?
And how to modify my code?
Thank you.
  4 件のコメント
Shuoze Xu
Shuoze Xu 2022 年 6 月 17 日
I'm sorry, I don't understand what you're trying to say
Walter Roberson
Walter Roberson 2022 年 6 月 18 日
編集済み: Walter Roberson 2022 年 6 月 18 日
there are exceptions:
  • mod(inf,i) is nan
  • mod(nan,i) is nan
  • problems if n is empty or not a scalar

サインインしてコメントする。

採用された回答

Voss
Voss 2022 年 6 月 18 日
Your driver code is calling isPrime two times.
% driver code
n = 9;
The first time, you only get a disp(b) from inside isPrime
[x1,x2]= isPrime(n);
0
The second time, you get a disp(b) from inside isPrime and then, after isPrime is done, you also disp the returned value from isPrime, which is a
disp(isPrime(n));
0 1
%function code
function[a,b] = isPrime(n)
% A number, n, is not prime if any number between 2 and n/2 divides the number without any remainder.
a = 1; % a = 1 means true
b = 0; % b = 0 means false
half = n/2; % get the half nums of n
for i = 2:half
if(mod(n,i)~=0) % if there is remainder
continue; % keep check
elseif(mod(n,i) == 0)
disp(b); % display false
break; % stop loop
end
disp(a);
end
end

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2022 年 6 月 17 日
Hint:
prime_detected = true
for appropriate things
if appropriate condition
prime_detected = false;
break;
end
end
  2 件のコメント
Shuoze Xu
Shuoze Xu 2022 年 6 月 17 日
How to return string on function?
Walter Roberson
Walter Roberson 2022 年 6 月 19 日
if prime_detected
a = "true";
else
a = "false";
end

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by