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
1 件のコメント
Walter Roberson
2021 年 9 月 25 日
k=2;
while(k>2)
You initialize k to 2, but you check k>2 which is immediately false.
採用された回答
DGM
2021 年 9 月 25 日
編集済み: DGM
2021 年 9 月 25 日
Consider:
a = next_prime(17560)
b = next_prime(5346551)
function k = next_prime(n)
k = n;
while true
if isprime(k)
break;
end
k=k+1;
end
end
3 件のコメント
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.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!