Help with function that uses a while statement to get the next largest prime number
1 view (last 30 days)
Show older comments
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 Comments
Walter Roberson
on 25 May 2021
Well, see the discussion below as to what the bug was in the code that was posted.
Answers (1)
Walter Roberson
on 9 Mar 2021
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.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!