algorithm - Time Complexity of Dependent for loop -
string str = "abcdefghijklmnopqrstuvwxyz"; int sum = 0; for(int i=0; i<str.length; i++) { int val = str[i]; while(val > 0) { sum = val % 62; val = val / 62; } }
i know parent loop executes n+1 time , child loop executes (val)^(1/62) times. parent loop time complexity o(n) don't find way calculate child loop. so, time complexity of above program ?.
thanks in advance.
let length of string written n.
n = str.length();
now, outer for-loop iterates whole length of string,i.e., n times. hence,outer for-loop complexity o(n).
talking child loop, inner while loop executes (val)^(1/62) times. so, can consider inner while-loop complexity o(log62 val).
all other statements take constant time-complexity.
therefore,net time complexity = o(n * log62 val).
last step because of :-
if f1(n) = o(g1(n)) , f2(n) = o(g2(n)),then f1(n) * f2(n) = o(g1(n) * g2(n))
as mentioned edward doolittle
in comment, reduce o(n * log2 val) log bases can converted base 2 constant division(by log262).
Comments
Post a Comment