필터 지우기
필터 지우기

Problem in creating a next_prime function

조회 수: 2 (최근 30일)
Danial Amin
Danial Amin 2020년 7월 24일
댓글: Danial Amin 2020년 7월 24일
I am trying to create a function for finding the immediate next prime number for the given input n. I am trying to run it online and the error is regarding server time out. I have checked my code a gazillion times and unable to grasp the issue. I have tried many different approaches, consulted online forums as well as got my function timed in MATLAB for various outputs even of the order 10^7. It stills displays the same server time out error. I am posting the code here to get comments on it by the teacher/TA.
function k=next_prime(n)
if n<2
k=1;
return;
end
if n>=2 & n<=1000
d=0;
while(isprime(d)==0)
d=n+1;
end
k=d;
end
if (rem(n,2)==0 & n>1000)
n=n+1;
end
if (rem(n,2)~=0 & n>1000)
partialsieve = primes(1000);
partialsieve(1) = [];
while true
if ~all(rem(n,partialsieve))
n = n + 2;
else
if (isprime(n)==1)
k = n;
break;
else
n = n + 2;
end
end
end
end
end

채택된 답변

Ferheen Ayaz
Ferheen Ayaz 2020년 7월 24일
It was unable to come out of the loop because d was stuck at n+1. The following changes will work.
function k=next_prime(n)
if n<2
k=1;
return;
end
if n>=2 & n<=1000
d=n+1;
while(isprime(d)==0)
d=d+1;
end
  댓글 수: 1
Danial Amin
Danial Amin 2020년 7월 24일
Thank you. Probably I just needed some break in my coding sessions and some coffee. Cheers.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by