Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

Time complexity of iterative division algorithm

Input: Two n-bit integers x and y, where y ≥ 1.

Output: The quotient and remainder of x divided by y.

if  x = 0, then return (q, r) := (0, 0);

q := 0;  r := x; 

while (r ≥ y) do       // takes n iterations for the worse case.

        { 
            q := q + 1;
            r := r – y
        };  // O(n) for each r – y, where y is n bits long.
return (q, r);

For the above algorihtm which mainly focuses on dividing two 'n' bit integers 'x' and 'y', can somone please explain and let me know the time complexity in terms of 'n'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Can't guarantee my explanation is flawless, but here it is anyway:

Just as written in comments, the time complexity is O(n), i.e. linear. In other words, the time it takes for the computer to execute the algorithm increases linearly with the increase of x or the decrease of y. Example: it will take 3 loops to get the result if x = 10 and y = 3, and it will take twice as many loops if we increase x by two to equal 20. That's what they call O(n).

Other time complexity types that exist are O(n^2) - quadratic time (ex: you increase x by 2 and the number of required loops increases by 4), O(n^3) - cubic (same logic), O(logn) - logarithmic time (the time is increasing less than linearly and at some point almost stops to increase at all).

And finally, there's O(1) - constant time. The above algorithm can be improved to have constant time if you type q=x/y and r=x%y instead of using the loops.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...