My function is running fine for small no but not for big no.Can anybody explain?

조회 수: 1 (최근 30일)
function k=next_prime(n)
k=2;
while(k>2)
if(isprime(k)==1)
if(k>n)
return
else
k=k+1;
end
else
k=k+1;
end
end

채택된 답변

DGM
DGM 2021년 9월 25일
편집: DGM 2021년 9월 25일
Consider:
a = next_prime(17560)
a = 17569
b = next_prime(5346551)
b = 5346571
function k = next_prime(n)
k = n;
while true
if isprime(k)
break;
end
k=k+1;
end
end
  댓글 수: 3
Walter Roberson
Walter Roberson 2021년 9월 25일
편집: Walter Roberson 2021년 9월 25일
What is an example of an input that it gives the wrong answer for?
Your code is slow. There is no point in testing any number that is lower than the input, n, because it does not matter if any of them are prime: all that matters is starting from n . And making sure that you carefully define what is intended to happen if the input is already a prime.
Nishant Raj
Nishant Raj 2021년 9월 25일
Ok,got it,my code is slow,thats why its taking a lot more time for big inputs.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by