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?
Show older comments
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 Comments
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
on 3 Feb 2022
Stephen23
on 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
on 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() )
Accepted Answer
More Answers (0)
Categories
Find more on Number games in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!