how to use conditional statement realizing prime function
Mostra commenti meno recenti
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 Commenti
Walter Roberson
il 17 Giu 2022
example:
Consider 35. 35/2 is 17 1/2 so we will examine 2 to 17. 35 is not divisible by 2 so continue; 35 is not divisible by 3 so continue. 35 is not divisible by 4 so continue. 35 is divisible by 5 so 35 is not prime
Consider 37. 37/2 is 18 1/2 so we will examine 2 to 18. 37 is not divisible by 2 so continue. 37 is not divisible by 3 so continue. 37 is not divisible by 4 so continue. Not divisible by 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 or 18 either. We have reached the end of the 2 to 37/2 range so 37 is a prime.
Walter Roberson
il 17 Giu 2022
if(mod(n,i)~=0) % if there is remainder
continue; % keep check
elseif(mod(n,i) == 0)
Under which circumstances could both of those tests be false? And why did you not put an else clause for the case where both are false?
Shuoze Xu
il 17 Giu 2022
Walter Roberson
il 18 Giu 2022
Modificato: Walter Roberson
il 18 Giu 2022
there are exceptions:
- mod(inf,i) is nan
- mod(nan,i) is nan
- problems if n is empty or not a scalar
Risposta accettata
Più risposte (1)
Walter Roberson
il 17 Giu 2022
Hint:
prime_detected = true
for appropriate things
if appropriate condition
prime_detected = false;
break;
end
end
2 Commenti
Shuoze Xu
il 17 Giu 2022
Walter Roberson
il 19 Giu 2022
if prime_detected
a = "true";
else
a = "false";
end
Categorie
Scopri di più su Number Theory in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!