# Factorial without the Command

조회 수: 62(최근 30일)
Sophie Culhane 2020년 9월 17일
댓글: Asad (Mehrzad) Khoddam 2020년 9월 17일
I am struggling to figure out how to compute a factorial without the use of the command. My task is to input a nonnegative integer and have the program compute its factorial.
Here is what I have for my script so far.
function Factorial = ex1(n)
%
%
if n = 0
Factorial = 1;
elseif n >= 1
Factorial = n(n-1)(n-2)(n-3)(3)(2)(1);
end
This program does not run, however I do not know where to go from here.

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

### 답변(4개)

James Tursa 2020년 9월 17일
편집: James Tursa 2020년 9월 17일
You could use either use a loop to multiply all of the numbers from 1 to n, or use recursion to multiply n by the factorial of n-1 (with some method of stopping the recursion). Were you instructed to use one of these methods? You could also use some different MATLAB functions for this, but I am not sure which ones would be allowed for your homework.
##### 댓글 수: 1표시숨기기 없음
Sophie Culhane 2020년 9월 17일
We are only allowed to use very basic commands. (this includes if construct, and the while loop)

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

function f = Factorial(n)
%
%
if n = 0 || n = 1
f = 1;
elseif n >= 1
f = n * Factorial(n-1);
end
##### 댓글 수: 1표시숨기기 없음
Rik 2020년 9월 17일
Why did you post this answer? Direct answers without an explanation encourages cheating.
If you don't respond I will delete this answer.

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

William 2020년 9월 17일
function f = Factorial(n)
%
if n = 0 || n = 1
f = 1;
elseif n >= 1
a = 1:n;
f = prod(a);
end
##### 댓글 수: 4표시숨기기 이전 댓글 수: 3
From the initial code, I thoughed that he wants to use a recursive function. So I modified the second part of the code. Later after seeing your comment and the code of the others, I noticed that he wants to use basic operations. That's all I did and thank you for your comment about being more carefull.

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

Using only basic operations:
function f = Factorial(n)
%
% initial value, 0! and 1!
f = 1;
if n > 1
for i=2:n
f = f * i;
end
end
##### 댓글 수: 1표시숨기기 없음
Stephen23 2020년 9월 17일
The if statement is superfluous: that for loop will only iterate for n>=2 anyway.

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

### Community Treasure Hunt

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

Start Hunting!

Translated by