runtime - Reducing a quadratic algorithm to linear time -
i trying write algorithm runs in o(n) time. essentially, takes integer n , multiplies sum coefficient. however, first attempt @ writing algorithm runs in o(n^2) time. (see below.) there way can reduce runtime?
for = 1 n num1 = i/n num2 = 0 j = n-1 num2 = num2 + 1/j result[i] = num1 * num2
your current approach running in quadratic time because, each element in sequence 1..n
iterating on sequence again. can remove work realizing need compute num2
summation once. after this, can reused.
num2 = 0 j = 1 n-1 num2 = num2 + 1/j = 1 n num1 = i/n if (i > 1) num2 = num2 - 1/(i-1) // reuse summation subtracting result[i] = num1 * num2 // off portion don't want value of
Comments
Post a Comment