Calculate factorial with 2 variables
5 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
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
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);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!