Q1 – At the following double-nested loop what will be the final value in m if loop does for n.
Of course it is not desired to do loop and see what the m is! Since n can be very large!
m = 0
for i = 1 to n-2
for j = i+1,n-1
for k = j+1,n
m += 1
Q2 – How did you find the answer? I mean what was the algorithm/technique that you used to solve the problem?
Q3 – What are your recommendation to solve similar problems?
Here is the answer that I was looking for:
Answer:
def ntn(n,k):
"""returns the number of iterations for k nested dependent loops(n)"""
return long(np.prod(n-np.arange(k,dtype=float)) /
np.prod(np.arange(k,dtype=float)+1))
example:
>>> ntn(1000,4) 41417124750L >>> ntn(1e20,3) 166666666666666650797607483335462097315368077619447843520512L
Answer:
Combination formula is as follows:
can be used for this purpose.
In Python there is
comb()function withinscipypackage which can be used too.However the following solution is much more flexible and faster and the resulting digits are much longer.
import numpy as np def ntn(n,k): """returns the number of iterations for k nested dependent loops(n)""" return long(np.prod(n-np.arange(k,dtype=float)) / np.prod(np.arange(k,dtype=float)+1))Examples: