What is the time complexity of the following code : int a = 0, i = N; while (i > 0) { a += i; i /= 2; }

Question

What is the time complexity of the following code : int a = 0, i = N; while (i > 0) { a += i; i /= 2; }
🧐 Not the exact question you are looking for?Go ask a question

Solution 1

The time complexity of the given code is O(log N).

Here's why:

The loop in the code runs as long as 'i' is greater than 0. In each iteration, 'i' is divided by 2. This means that 'i' is halved in every step.

The number of times you can halve a number until you reach 1 (or less) is log base 2 of Knowee AI StudyGPT is a powerful AI-powered study tool designed to help you to solve study prob

Knowee AI StudyGPT is a powerful AI-powered study tool designed to help you to solve study problem.
Knowee AI StudyGPT is a powerful AI-powered study tool designed to help you to solve study problem.
Knowee AI StudyGPT is a powerful AI-powered study tool designed to help you to solve study problem.
Knowee AI StudyGPT is a powerful AI-powered study tool designed to help you to solv

This problem has been solved

Similar Questions

What is the time complexity of the following code : int a = 0, i = N; while (i > 0) { a += i; i /= 2; }

The time complexity of the  following code snippet isc=0; while (n>=1) {for(i=1;i>=n;i++){ c++;}n=n/2;}

What is the time complexity of the following code :int i, j, k = 0;for (i = n/2; i <= n; i++) { for (j = 2; j <= n; j = j * 2) { k = k + n/2; }}

What is the time complexity of the following code fragment?for(i=1; i<n; i= i*2)          a[i]=0;

What is the time complexity of the following code fragment?for(i=1; i<n; i= i*2)          a[i]=0; Group of answer choicesO(n/2)O(n^(1/2))O(n^2)O(log n)

1/3