Knowee
Questions
Features
Study Tools

Cho biết độ phức tạp của đoạn mã giả sau dùng ký hiệu big-O.s = 0for (i = 1; i <= n; i *= 3)s = s + a[i]a.O( n )b.O(n^2)c.O(logn)d.O(nlogn)Clear my choice

Question

Cho biết độ phức tạp của đoạn mã giả sau dùng ký hiệu big-O.

s = 0
for (i = 1; i &lt;= n; i *= 3)
    s = s + a[i]

a. O( n )
b. O(n^2)
c. O(logn)
d. O(nlogn)

Clear my choice

🧐 Not the exact question you are looking for?Go ask a question

Solution

1. Break Down the Problem

We need to analyze the pseudocode provided to determine its time complexity using Big-O notation. The pseudocode is structured as follows:

s = 0
for (i = 1; i <= n; i *= 3)
    s = s + a[i]

2. Relevant Concepts

The time complexity of a loop can be analyzed by examining how the loop variable changes over each iteration and how many times the loop will execute in relation to the input size n n .

3. Analysis and Detail

  • The loop starts with i=1 i = 1 .
  • In each iteration, i i is multiplied by 3 (i *= 3).
  • The loop continues until i i exceeds n n .

To find out how many iterations the loop runs, we can express i i in terms of n n :

  1. In the first iteration: i=1 i = 1
  2. In the second iteration: i=3 i = 3
  3. In the third iteration: i=32=9 i = 3^2 = 9
  4. In the fourth iteration: i=33=27 i = 3^3 = 27
  5. And so on...

We need to determine when i i becomes greater than n n :

3kn 3^k \leq n

Taking the logarithm base 3 of both sides, we get:

klog3(n) k \leq \log_3(n)

Thus, the number of iterations k k can be approximated by:

kO(log3(n))=O(log(n)) k \approx O(\log_3(n)) = O(\log(n))

4. Verify and Summarize

The loop runs logarithmically with respect to n n since it increases in powers of 3. Therefore, the time complexity of this pseudocode is O(logn) O(\log n) .

Final Answer

The time complexity of the given pseudocode is c. O(log n).

This problem has been solved

Similar Questions

Cho biết độ phức tạp của đoạn mã giả sau dùng ký hiệu big-O.int F(int n)if (n <= 2)return 1elsereturn F(n − 2) * F(n − 2)a.O(2^(n/2))b.O(2^n)c.O(n^2)d.O( n )

A growth function that is O(n) is ____________________   A. constant B. logarithmic C. linear D. quadratic E. exponential

Hôn nhân tiến bộ là:a.Không chấp nhận sự áp đặt của cha mẹb.Hôn nhân xuất phát từ tình yêuc.Tự do trong việc lựa chọn người kết hônd.Bao gồm các đáp án

Luật phòng chống tác hại rượu bia quy định về mức xử phạt tối đa đối với việc vận chuyển rượu, bia có nồng độ cồn cao hơn bao nhiêu?a.0,08%b.0,03%c.0,1%d.0,05%

Time complexities of three algorithms are given. Which should execute the slowest for largevalues of N?(A) O(N^0.5)#(B) O(n)(C) O(logN)(D) O(log2n)(E)O(NlogN

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.