MATLAB Answers

Calculate factorial with 2 variables

3 views (last 30 days)
Dai Nguyen
Dai Nguyen on 15 Sep 2020
Commented: Dai Nguyen on 15 Sep 2020
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 Comments

Sign in to comment.

Answers (2)

John D'Errico
John D'Errico on 15 Sep 2020
Edited: John D'Errico on 15 Sep 2020
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 on 15 Sep 2020
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 Comments

Sign in to comment.

Tags

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by