Problem Set 0

We have some code reading exercises here. Please write your understanding of what the code does. Strive for precision, clarity and brevity.

Do not explain what each line of code does. State what the whole program or function does; how the writer intended this code to be used is the focus.

1. What a start, eh?

What is the purpose of this C code fragment:

p -= (p < 0) * 2 * p;

2. Let us loop around

What is the purpose of this function?

1
2
3
4
5
6
7
 bool asimov(int n) {
     int r = 0;
     while (r * r * r < n) {
         ++r;
     }
     return r * r * r == n;
 }

3. Let us chop it up

What is the purpose of this function?

1
2
3
4
5
6
7
8
9
 bool bradbury(int n) {
     while (n > 0) {
         if (n % 2 == 1) {
             return false;
         }
         n /= 10;
     }
     return true;
 }

4. Look up for answers

What is the purpose of this function?

1
2
3
4
5
6
7
 int clarke(int n) {
     int q = 0;
     while (q * q < n) {
         ++q;
     }
     return q;
 }

5. And finally, double and quit

What is the purpose of this function?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
 double doctorow(double alpha, int beta) {
     if (beta < 0) {
         alpha = 1.0/alpha;
         beta *= -1;
     }
     double gamma = 1.0;
     while (beta > 0) {
         if (beta % 2 == 1) {
             gamma *= alpha;
         }
         alpha *= alpha;
         beta /= 2;
     }
     return gamma;
 }