A function to find prime number

조회 수: 2 (최근 30일)
Takashi Fukushima
Takashi Fukushima 2019년 11월 13일
댓글: Takashi Fukushima 2019년 11월 14일
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....

채택된 답변

James Tursa
James Tursa 2019년 11월 13일
편집: James Tursa 2019년 11월 13일
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
James Tursa
James Tursa 2019년 11월 14일
Put a semi-colon at the end of the assignment line to suppress the output:
result=isPrime(number);
Takashi Fukushima
Takashi Fukushima 2019년 11월 14일
Thank you so much! I made it!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

John D'Errico
John D'Errico 2019년 11월 13일
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
Takashi Fukushima
Takashi Fukushima 2019년 11월 13일
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...

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by