ProgrammingHard
Which C code correctly counts the digits of n = 10^9 in a fast enough way for many queries?
- A. for (int i = 0; i < n; i++) if (n == i * 10) d++;
- B. int d = (int)log10(n);, with the value not used
- C. int d = n; for (int i = 0; i < d; i++) d /= 10;
- D. unsigned long long m = n; int d = 0; do { d++; m /= 10; } while (m);
Correct answer: D. unsigned long long m = n; int d = 0; do { d++; m /= 10; } while (m);
The do-while divides by 10 once per digit, so it takes about 10 steps for 10^9. The other versions loop over n itself or produce the wrong count.
More C Programming questions
- The sum of the digits of n = 10^9 - 1 is computed with a loop that divides by 10 each time. How many loop iterations run?
- To list all primes up to 10^7 in C with memory and time that fit, which is the best choice?
- For each of Q = 10^5 queries, a program sums an array prefix of length up to N = 10^5 by a loop. What is the total cost?
- A recurrence T(n) = T(n - 1) + n is solved by a program with a loop over the recursion. What is the total cost in terms of n?
- What is the total number of elements in a triangle of rows 1 to 10, where row k has k elements?
- A program runs a loop body 10^8 times and each iteration does one multiply and one add on ints. Roughly how long does this take on typical…