I tried to write a code to find the next smallest prime number greater than any given positive integer. My code is stuck in infinity loop, how can I find where is the problem?
Afficher commentaires plus anciens
function k = next_prime(n)
t = 2;
if isscalar(n) && fix(n) == n && n > 0
while t > 0
if isprime(t) && t > n
k = t;
return
else
t = t + 1;
end
end
end
4 commentaires
What n are you passing in? The code seems to work for me. Of course, it is going to take a long time for large n as it is not efficient code.
N = randi([2 5000])
next_prime(N)
function k = next_prime(n)
t = 2;
if isscalar(n) && fix(n) == n && n > 0
while t > 0
if isprime(t) && t > n
k = t;
return
else
t = t + 1;
end
end
end
end
Nipun Vashistha
le 3 Fév 2022
Stephen23
le 3 Fév 2022
"Could you please suggest me how can I make it more efficient? "
Search this forum for "prime number" and you wll find plenty of discussions on how to do this efficiently.
The search field is in the top right-hand corner of the page.
Walter Roberson
le 3 Fév 2022
There is no point in testing any value 1 to n for being prime when you are using isprime() to test for prime numbers.
(There can be reason to test for them being prime if you are using a different technique to find prime numbers, one that does not involve using isprime() )
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Arduino Hardware dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
