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?
Mostra commenti meno recenti
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 Commenti
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
il 3 Feb 2022
Stephen23
il 3 Feb 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
il 3 Feb 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() )
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Arduino Hardware 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!
