Calculate factorial with 2 variables

조회 수: 5 (최근 30일)
Dai Nguyen
Dai Nguyen 2020년 9월 15일
댓글: Dai Nguyen 2020년 9월 15일
Hi I want to calculate a factorial of these 2 integer input variables, but for some reason it didn't work. Please help
m=input('enter the value of m');
n=input('enter the value of n');
y = prod([m+1 : n]) / prod([1 : n-m]);
function y = special_fact1(n, m)
% using loops to calculate the numerator
t1 = 1;
for i = m+1 : n
t1 = t1 * i;
end
% using loops to calculate the denominator
t2 = 1;
for i = 1 : n-m
t2 = t2 * i;
end
% assembling the appropriate terms
y = t1/t2;
end

답변 (2개)

John D'Errico
John D'Errico 2020년 9월 15일
편집: John D'Errico 2020년 9월 15일
Why do you feel you need to use loops? You should never write your own code for something that is far better computed using an existing code? (Remember, those who wrote nchoosek write code for a living, and they truly understand MATLAB as well as numerical methods.)
Anyway, what you are asking for is not a factorial, but a binomial coefficient. You could compute it as:
y = factorial(n)/factorial(n-m)/factorial(m);
or,
y = prod([m+1 : n]) / prod([1 : n-m]);
Which is not surprisingly just
y = nchoosek(n,m);
Anyway, the code you wrote DOES work. For example...
>> n = 12;
>> m = 7;
>> prod([m+1 : n]) / prod([1 : n-m])
ans =
792
>> nchoosek(n,m)
ans =
792
>> factorial(n)/factorial(n-m)/factorial(m)
ans =
792
>> special_fact1(n,m)
ans =
792
It looks like what you wrote did work. They all agree, as they should.
Knowing why it did not work for you requires a crystal ball. When you have an error, you need to show us the complete error message. Show how you called the code. Just saying it did not work is meaningless, because in fact, what you wrote DOES work.

David Hill
David Hill 2020년 9월 15일
Very easy to overrange factorial, might consider symbolic numbers
a=input('a');
b=input('b');
a=sym(a);
b=sym(b);
y=prod(a+1:b)/prod(1:b-a);

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by