Clear Filters
Clear Filters

Help with function that uses a while statement to get the next largest prime number

1 view (last 30 days)
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

Answers (1)

Walter Roberson
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.
  1 Comment
Jessamyn Johnson
Jessamyn Johnson on 9 Mar 2021
ahhh thank you I can't believe I put in isscalar istead of isprime!!! haha I feel so stupid, the function works now that I have actually put in isprime. oh my gosh how did I miss that

Sign in to comment.

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!