Help with function that uses a while statement to get the next largest prime number
1 回表示 (過去 30 日間)
古いコメントを表示
Hi, I am working on an assignment that requires finding the next largest prime number k after the input n. I feel like I am not succesfully using the while loop statement and I was wondering if anyone had suggestions as my output is just n+1. I know I am structuring this in a way that my i being used in my last if statement (i=k) is not coming from the while loop and thats about as far as I can get.
function k = next_prime1(n)
if n<1||~isscalar(n)||n==~fix(n)
error('integer not a whole positive number')
else
i=n+1;
while ~isscalar(i)
i=i+1;
end
if isscalar(i)
k=i
end
end
2 件のコメント
Walter Roberson
2021 年 5 月 25 日
Well, see the discussion below as to what the bug was in the code that was posted.
回答 (1 件)
Walter Roberson
2021 年 3 月 9 日
isscalar() is a test to see if size() of the argument is all 1's -- not empty, not 2D, just a single element.
isscalar() has nothing to do with whether a value is prime.
isscalar(n) is a good test for valid inputs. But you should do it first
if ~isnumeric(n) || ~isscalar(n) || n < 1 || n==~fix(n)
otherwise if the user passes in something non-scalar you would be testing that non-scalar value against 1, which would give a non-scalar result and then the || would fail. Postpone all your numeric tests until you know that the input is a numeric scalar.
But after that... you should be testing for prime, not testing for scalar.
参考
カテゴリ
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!