Calculate factorial with 2 variables

6 ビュー (過去 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.
  1 件のコメント
Dai Nguyen
Dai Nguyen 2020 年 9 月 15 日
got it thank you

サインインしてコメントする。


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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by