CSci 280: Algorithms and problem-solving paradigms
Home Syllabus Classwork

printable version

Quiz 1

[1] [2] [3] [4] [5] [6] [7]

Problem Q1.1.

[8 pts] We can define the trailing zeroes of an integer k as the zeroes following the last 1 in k's binary representation; for example, the number 20 (represented in binary as 10100) has two trailing zeroes.

The below method returns the total number of trailing zeroes for all integers from 1 to its parameter n. Given the number 10, the program fragment would return 0 + 1 + 0 + 2 + 0 + 1 + 0 + 3 + 0 + 1 = 8.

Using big-O notation in terms of its parameter n, what is the running time of the below program fragment? Give the tightest and simplest bound you can, and justify your answer.

public static int countTrailingZeroes(int n) {
    int total = 0;
    for(int num = 1; num <= n; num++) {
        for(int div = 2; num % div == 0; div *= 2) {
            total++;
        }
    }
    return total;
}