Hypothetical Factorial Question Solution

조회 수: 7 (최근 30일)
Deborah Brooks
Deborah Brooks 2022년 5월 19일
댓글: Stephen23 2022년 5월 19일
Hi, I'm new to MATLAB and I'm teaching myself. I have made this code to answer what is the factorial of 'n'. My question is - is it possible to write code that will solve this backwards? i.e. if I'm given 120 can it solve for the answer of 5? Thanks in advance!
n = 5;
nfact = 1;
for i = 1:n
nfact = nfact*i;
end
disp(nfact)
  댓글 수: 1
David Goodmanson
David Goodmanson 2022년 5월 19일
편집: Torsten 2022년 5월 19일
HI Deborah,
One straightforward way would be: divide by 2. If that result is an integer, divide it by 3. If that result is an integer, divide it by 4 ... keep going until the division either returns 1 somewhere along the line, in which case the starting point was the factorial of the last-used integer, or does not return 1 and returns values less than 1, in which case the starting point was not the factorial of an integer. Programming that up should give you more good practice with Matlab.
If you go this direction you will of course have to check if a number is an integer. Matworks has an 'isinteger' function, but somewhat perversely it does not work for ordinary Matlab double precision numbers. But you can use
floor(n) == n
and if the result is true, n is an integer.

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

답변 (2개)

Chunru
Chunru 2022년 5월 19일
x = 120;
nfact = 1;
for i = 1:x
nfact = nfact*i;
if nfact==x
fprintf("%d = %d!\n", x, i)
break
elseif nfact>x
fprintf('x is not a factorial number. \n')
break;
end
end
120 = 5!
  댓글 수: 2
the cyclist
the cyclist 2022년 5월 19일
You might want to be careful about floating-point error in the equality check, and instead use something like
tol = 1.e-6;
if abs(nfact-x) < tol
Chunru
Chunru 2022년 5월 19일
This is supposed to be integer operation of factorial.

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


the cyclist
the cyclist 2022년 5월 19일
편집: the cyclist 2022년 5월 19일
I don't really intend this to be a serious answer to your question, but according to the internet, this formula will work up to N==170.
% Original number
N = 170;
% Factorial of the number
nfact = factorial(N);
% Recover original number
n = round((log(nfact))^((303*nfact^0.000013)/(144*exp(1))) + 203/111 - 1/nthroot(nfact,exp(1)))
n = 170
Looks like this is based on Stirling's approximation.
Also, note that 171! is too large to be represented as double precision in MATLAB:
factorial(170)
ans = 7.2574e+306
factorial(171)
ans = Inf
  댓글 수: 1
Stephen23
Stephen23 2022년 5월 19일
Even 23! is too large to be accurately represented using the DOUBLE class:
factorial(sym(23))
ans = 
25852016738884976640000
sym(factorial(23))
ans = 
25852016738884978212864

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

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by