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

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -