سوال ۶۷ کنکور ارشد علوم کامپیوتر ۱۴۰۰
پس از اجرای قطعه کد زیر، k از چه مرتبهای است؟
k = 0;
for (i = 0; i < n; i = i + 1)
for (j = 1; j < n; j = j + i)
k = k + 1;
پاسخ صحیح: گزینهٔ B —
The value of equals the total number of inner-loop iterations summed over all values of .
Counting the inner loop for a fixed
For a fixed outer value , the inner loop starts at and advances by a step of each time, running while :
The number of iterations is
Summing over all
Adding the contributions for :
The harmonic number satisfies , so
The harmonic sum is the key: the inner loop does not run times for every — it runs only times, and grows like , not like . That is why the total is and not .
Numerically, dividing the exact count by tends to as grows, while dividing by stabilizes near a constant — confirming .
Pitfall: Two nested loops up to do not automatically give . Here the inner step size grows with , shrinking the inner count to and collapsing the double sum into a harmonic series . (Strictly, the literal pass keeps fixed; the intended analysis takes , where the step is meaningful.)