MATLAB Answers

0

A function to find prime number

Takashi Fukushima さんによって質問されました 2019 年 11 月 13 日 21:23
最新アクティビティ Takashi Fukushima さんによって コメントされました 2019 年 11 月 14 日 19:11
Hello,
I wrote a function to find a prime number and would like to run it to find all prime numbers up to 100 from my starting point. However, I get an error saying "too many output arguments".
Here is what I have...
function isPrime(number)
tf=isprime(number);
if tf==true
disp(number)
end
end
starting_point=input("Enter your number: ");
while starting_point<100
disp(isPrime(starting_point))
starting_point=starting_point+1;
end
I would really appreciate if anyone can help me with this problem....

  0 件のコメント

サインイン to comment.

2 件の回答

James Tursa
Answer by James Tursa
on 13 Nov 2019 at 22:58
Edited by James Tursa
on 13 Nov 2019 at 22:58
 Accepted Answer

Your function doesn't return anything, so when you try to use its output you get an error. Change this:
function isPrime(number)
to this
function tf = isPrime(number)

  3 件のコメント

Thank you so much for your advice.
Based on your advice, I fixed it like this...
function [result]=isPrime(number)
tf=isprime(number);
if tf==true
result=number;
else
result=0;
end
end
number=input("Enter your number: ");
while number<100
result=isPrime(number)
number=number+1;
end
However, the problem here is that output shows "result=0" which I don't want it to show. I am not sure how I can surpress the appearance.
James Tursa
on 14 Nov 2019 at 2:38
Put a semi-colon at the end of the assignment line to suppress the output:
result=isPrime(number);
Thank you so much! I made it!

サインイン to comment.


John D'Errico
Answer by John D'Errico
on 13 Nov 2019 at 23:00

Hey, you wrote some code! Credit for that. :-)
But what did you do?
function isPrime(number)
tf=isprime(number);
if tf==true
disp(number)
end
end
This function has NO outputs! None at all. It dumps somethign to the command window, but that is all. It does NOT return a result.
But then, how do you use it?
disp(isPrime(starting_point))
you use it, expecting an output.
What was the error message?
"too many output arguments"
So you wrote a function that returns no arguments, but then you used it expecting an output argument. Therein lies the problem. The fact is however, you are not using any output from isPrime, and it already dumps a comment to the command window.
Just change the code you use to this:
starting_point=input("Enter your number: ");
while starting_point<100
isPrime(starting_point)
starting_point=starting_point+1;
end

  1 件のコメント

Thank you so much for your answer.
I think that it's the simplest and the most beautiful code for this problem.
Also, I made some progress which you can see above on James's comment although I still have a problem there...

サインイン to comment.



Translated by