问题
I need a function that can solve the following: for a binomial function nCr=k, given r and k find n. in mathematics nCr=n!/r!(n-r)! I tried following but it doesn't solve it. for example 8C6=28, for my function the inputs are 6 and 28 and i want to find 8. This may not have exact integer number so I want to find an x>=n.
"""I am approaching it this way, i.e. find the solution of a polynomial function iteratively, hope there is a better way"""
def find_n(r,k):
#solve_for_n_in(n*(n-1)...(n-r)=math.factorial(r)*k
#in the above example solve_for_n(n*(n-1)(n-2)(n-3)(n-4)(n-5)=720*28)
sum=math.factorial(r)*k
n=r+1
p=1
while p<sum:
p=1
for i in range(0,r+2):
p*=(n-i)
n+=1
return n-1
Thanks.
回答1:
I solved it the following way, i.e. find the solution of a polynomial function iteratively, hope there is a better way.
def find_n(r,k):
#solve_for_n_in(n*(n-1)...(n-r)=math.factorial(r)*k
#in the above example solve_for_n(n*(n-1)(n-2)(n-3)(n-4)(n-5)=720*28)
target=math.factorial(r)*k
n=r+1
p=1
while p<target:
p=1
for i in range(0,r+2):
p*=(n-i)
n+=1
return n-1
回答2:
Here's a solution which uses fminsearch
. You'll want to minimize the absolute difference between nchoosek(n, r)
and k
. However, you'll likely run into undefined values for nchoosek
, so it's better to define it from scratch. Don't use factorial
either though, as it's undefined for negative integers. Instead, use gamma
(read about this on Wikipedia if you don't know).
r = 6;
k = 28;
toMinimize = @(n) abs(gamma(n+1) / (gamma(r+1) * gamma(n-r+1)) - k);
Be smart about the initial conditions:
for n = 1:10
[res(n, 1), fval(n, 1)] = fminsearch(toMinimize, n);
end
[res fval]
Now you'll see you should only trust initial conditions n0 >= 5
, for which the answer is n = 8
.
ans =
1.42626953125 27.9929874410369
1.42626953125 27.9929874410369
3.5737060546875 27.9929874410073
3.57373046875 27.9929874410369
8 0
8.00000152587891 5.2032510172495e-05
8.00000152587891 5.20325100552554e-05
8 0
7.99999694824218 0.000104064784270719
8 0
来源:https://stackoverflow.com/questions/35753215/for-binomial-function-ncr-k-given-r-and-k-find-n