Help with function that uses a while statement to get the next largest prime number
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Walter Roberson
il 25 Mag 2021
Well, see the discussion below as to what the bug was in the code that was posted.
Risposte (1)
Walter Roberson
il 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.
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!