سوال ۶۸ کنکور ارشد علوم کامپیوتر ۱۴۰۰
پس از اجرای قطعهای که زیر، k از چه مرتبهای است؟
k = 0;
for (i = 1; i < n; i = i + 1)
for (j = 1; j < i; j = j + 1)
k = k + i + j;
پاسخ صحیح: گزینهٔ C — n^{3}
The question asks for the order of the final value of , not the running time. We must add up every increment over all executions of the inner loop body.
Setting up the double sum
The outer index runs from to , and for each the inner index runs from to . Each pass adds to :
Evaluating the inner sum
For a fixed there are terms:
Summing over
Using and , the dominant term is cubic:
Intuitively, the body runs about times (that is the time complexity, ), and each increment is itself , so the accumulated value is .
Numerically, as grows (e.g. at , at ), while — confirming order , which is option 3.
Exam trick: Separate time from value. The loops execute times, but you are asked for the magnitude of . Because each increment grows linearly with , the stored value is one order higher than the iteration count: , not .