ProgrammingModerate
In a loop for (i = 0; i < n; i++) x = x * 2 % m; with m = 1000000007 and x kept as long long, what is the cost?
- A. O(n) multiplications and modulo operations, each constant time
- B. O(n^2), since the modulo costs n
- C. O(log n), since the value doubles
- D. O(2^n), since the value doubles each time
Correct answer: A. O(n) multiplications and modulo operations, each constant time
Each iteration does a constant amount of work, so the loop is linear in n. The value stays reduced modulo m.
More C Programming questions
- Which loop computes the number of trailing zeros of n in O(number of zeros) time for an unsigned n greater than zero?
- A loop with i starting at 1 and i = 2 until i > n runs how many times for n = 1000?
- A program uses a while loop that finds the smallest power of two at least n for n = 1000, starting from 1. What value does it return?
- int i = 0; for (; i < 5; ) i += 2; printf("%d", i); What is printed?
- int s = 0; for (int i = 1; i <= 4; i++) s += i (i % 2 ? 1 : -1); printf("%d", s); What is printed?
- int n = 0; while (++n < 10 && n % 4); printf("%d", n); What is printed?