Salta al contenuto
Note per Studenti Foundations of Computer Science - Mock Exam 2 Report

Foundations of Computer Science - Mock Exam 2

Questa pagina non ha ancora la versione ripasso: qui sotto c'è il testo completo.

In questa pagina 4

Mock exam proposed for practice, built on the model of the written tests of the equivalent course in Italian (Fondamenti di Informatica, Information Engineering, UniPD: the theory quizzes and the Java practical tests). It is not an official past paper. Duration 2 hours, 30 points, no material allowed. Exercise 1 (8 points): eight short questions of 1 point each, closed or numeric answers, about 25 minutes. Exercise 2 (10 points) and Exercise 3 (12 points): Java problems. In the Java problems the time required is part of the specification, and all the code in the solutions was compiled and run with JDK 21 on the examples and on random tests.

Exercise 1 (points 8)

Eight questions, 1 point each.

Q1. Which statement describes the von Neumann model?

  • a) Program and data are stored in two separate memories, each with its own bus.
  • b) Program and data are stored in the same memory, and the CPU executes the instructions one after the other, fetching them from memory.
  • c) The program is stored in ROM and the data in RAM; the CPU has no registers.
  • d) The CPU executes all the instructions of the program at the same time.

Q2. A program is stored in consecutive memory cells, one instruction per cell:

address instruction
0 LOAD A
1 ADD B
2 JUMP 5 (continue from address 5)
3 SUB C
4 STORE D
5 STORE E
6 HALT

The program counter (PC) starts at 0. Give: a) the value of the PC right after the fetch of the instruction at address 2; b) the value of the PC right after its execute step; c) the number of instructions executed from the start up to and including HALT.

Q3. A CPU has a clock frequency of 4 GHz. a) What is the clock period in nanoseconds? b) How many bytes are there in 2 GiB, and by how many bytes does this exceed 2 GB?

Q4. In Java an int is a 32-bit two's complement integer, and an overflow gives no error. What do b, c and -b contain after this code?

java
int a = 2147483647;      // 2^31 - 1, the largest int
int b = a + 1;
int c = a * 2;
// then evaluate -b

Q5. What does the program print?

java
public class Q5 {
    static void f(int n, int[] v, int[] w) {
        n = n + 10;
        v[0] = n;
        w = new int[3];
        w[1] = 99;
    }

    public static void main(String[] args) {
        int n = 1;
        int[] v = {0, 0};
        int[] w = {5, 5, 5};
        f(n, v, w);
        System.out.println(n + " " + v[0] + " " + w[0] + " " + w[1]);
    }
}

Q6. After this code, what is count? And what would count be with 5 replaced by 1000 in both conditions? What is the order of growth in nn when 5 is replaced by nn?

java
int count = 0;
for (int i = 0; i < 5; i++)
    for (int j = i; j < 5; j++)
        count++;

Q7. What does the code print? (Write each output line; a space is printed after every number.)

java
for (int i = 1; i <= 4; i++) {
    for (int j = 1; j <= 4; j++) {
        if (j == i) continue;
        if (j > 3) break;
        System.out.print(i * j + " ");
    }
    System.out.println();
}

Q8. The same machine as in Q2 runs this program (one instruction per cell, JNZ R1, 2 means: if register R1 is not zero, continue from address 2, otherwise go on with the next address; R1 and R2 are registers):

address instruction
0 LOAD R1, 3 (put 3 in R1)
1 LOAD R2, 0
2 ADD R2, R1 (R2 = R2 + R1)
3 SUB R1, 1 (R1 = R1 - 1)
4 JNZ R1, 2
5 STORE R2 (write R2 to memory)
6 HALT

Give: a) the final value of R2; b) the number of instructions executed up to and including HALT; c) the value of the PC right after the execute step of JNZ, for its first and for its last execution.

Show the result
  • Q1: b)
  • Q2: a) 3; b) 5; c) 5 instructions (addresses 0, 1, 2, 5, 6).
  • Q3: a) 0.25 ns; b) 231=2 147 483 6482^{31} = 2\,147\,483\,648 bytes, which is 147 483 648147\,483\,648 bytes more than 2 GB (2 000 000 0002\,000\,000\,000).
  • Q4: b = −2147483648-2147483648, c = −2-2, -b = −2147483648-2147483648.
  • Q5: 1 11 5 5
  • Q6: count = 15; with 1000, count = 500500; order n2n^2 (exactly n(n+1)/2n(n+1)/2).
  • Q7:
2 3 
2 6 
3 6 
4 8 12 
  • Q8: a) 6; b) 13 instructions; c) 2 the first time, 5 the last time.
Show the full solution

Q1. The von Neumann model keeps both data and program in the same memory and the CPU runs a cycle on instructions taken one after the other (Computer ArchitectureModern computers follow the von Neumann model: a CPU (ALU, control unit, registers, cache) driven by a clock runs a fetch-decode-execute cycle on programs and data stored in the same memory; memory is a hierarchy from fast, small and volatile (registers, cache, RAM) to slow, large and persistent (SSD, disk, tape); CPU, memory and I/O talk through a bus made of data, address and control lines on the motherboard.Computer Architecture →). a) describes separate memories for program and data, which is not the von Neumann model, c) is wrong because the CPU has registers and the program is loaded into RAM, d) contradicts the sequential cycle. Answer b).

Q2. The cycle has three steps: fetch (load the instruction into the instruction register and increase the PC), decode, execute. The PC is increased at the end of the fetch, so right after fetching the instruction at address 2 the PC is 2+1=32 + 1 = 3 (a). Only the execute step of JUMP 5 writes 5 into the PC (b): this is how jumps break the sequential order. Executed addresses: 0, 1, 2, then 5 (addresses 3 and 4 are skipped), then 6 HALT: 5 instructions (c). Typical error: answering 2 for (a) (the PC is already incremented) or counting 7 instructions.

Q3. a) Period τ=1/f=1/(4×109 Hz)=0.25×10−9\tau = 1/f = 1/(4\times 10^9\ \text{Hz}) = 0.25\times 10^{-9} s =0.25= 0.25 ns. b) The binary prefix gives 1 GiB =230= 2^{30} bytes, so 2 GiB =231=2 147 483 648= 2^{31} = 2\,147\,483\,648 bytes, while 2 GB =2×109= 2\times 10^9 bytes; the difference is 147 483 648147\,483\,648 bytes. Typical error: treating GiB and GB as the same (see the table of units in Computer ArchitectureModern computers follow the von Neumann model: a CPU (ALU, control unit, registers, cache) driven by a clock runs a fetch-decode-execute cycle on programs and data stored in the same memory; memory is a hierarchy from fast, small and volatile (registers, cache, RAM) to slow, large and persistent (SSD, disk, tape); CPU, memory and I/O talk through a bus made of data, address and control lines on the motherboard.Computer Architecture →).

Q4. In 32-bit two's complement the range is [−231,231−1][-2^{31}, 2^{31}-1], so aa is the largest value, and the correct sum 2312^{31} is outside the range: the result wraps around modulo 2322^{32} and the pattern 1000...0 is −231-2^{31} (Representation of InformationEverything in a computer is a sequence of bits, so each kind of information needs a coding. Natural numbers use positional notation in base 2 (conversion by repeated division by 2); signed integers use two's complement (range from minus 2 to the n minus 1 up to 2 to the n minus 1, minus 1), where negation is invert-all-bits-and-add-1, sums are plain binary sums and overflow is detected on the two top carries; hexadecimal groups bits in fours; fractions use fixed point or IEEE 754 floating point (sign, exponent in excess 127, 23-bit fraction) and are only approximate; characters are unsigned integers in a code table (ASCII, Unicode); images, video and sound are stored as numbers too (pixels, frame differences, samples).Representation of Information →). So b =−2147483648= -2147483648. For c: 2(231−1)=232−2≡−2(mod232)2(2^{31}-1) = 2^{32} - 2 \equiv -2 \pmod{2^{32}}, so c =−2= -2. Finally −b-b: one's complement of 1000...0 is 0111...1, plus 1 gives 1000...0 again, so -b is still −2147483648-2147483648 (the special case of the most negative integer). Java does not signal overflow in int arithmetic: the program continues with a wrong value (Java - Language BasicsJava (Sun Microsystems, 1991) is an object-oriented language designed to be simple and CPU-independent ("write once, run anywhere"). Every program is made of classes; an executable class needs a main method, and the public class name must match the file name (Hello.java). The source is compiled by javac into bytecode (Hello.class), the machine code of the Java Virtual Machine, which the Java interpreter (java Hello) runs, translating on the fly into real CPU instructions; so Java is both compiled and interpreted, portable at source and bytecode level and of intermediate efficiency. Errors are syntax (found by the compiler) or logical (found only by testing). The grammar has five token types (keywords, identifiers, literals, separators, operators). Complements: loop end tests with less-than, sentinel values and the loop and a half, break and continue, the conditional operator and switch.Java - Language Basics →).

Q5. Java passes everything by value (Java - Classes, Objects and ScannerIn Java a class defines instance variables (usually private), a constructor and methods; objects are created with new and used through reference variables. A method call p1.getDistanceFrom(p2) has an implicit argument (the object p1, available inside the method as this) and explicit arguments (p2). Arguments are always passed by value: a copy of the value or of the reference is passed. Comparing references with == tests whether they point to the same object, while equals() compares the content; null is tested with ==; floating point numbers are compared with a tolerance. Public methods are documented with javadoc comments (param, return). The Scanner class splits a string or the standard input into tokens with hasNext() and next() and offers hasNextInt, hasNextDouble, hasNextLine; the end of the standard input is ctrl+z then return on Windows and ctrl+d on Unix. Worked exercises: the MyPoint2D point class with its tester, and the specification of a MyComplex class.Java - Classes, Objects and Scanner →, Java - MyComplex, Methods and RedirectionFull MyComplex class (complex numbers): private re and im, constructors chained with this(...) as first statement, methods add, sub, mult, div (= mult by inv), inv, conj, mod, re, im, toString, equalsApprox with a private static helper using a relative tolerance 1E-14. Style rules: give constructor arguments names different from the instance variables (or use this.re = re), never overwrite method arguments, avoid the stray semicolon after if/for/while. Concepts: accessor vs modifier methods (immutable classes only have accessors, e.g. MyComplex and String), boolean methods, formal vs actual arguments, Java passes everything by value (a copy of the number or of the reference), so a method can change the state of an object it receives but cannot make the caller's variable refer to another object; instance methods use this and instance variables, static methods only their explicit arguments; private methods can be called only inside the class. Finally standard input/output redirection with < > >> from the terminal.Java - MyComplex, Methods and Redirection →):

  • n is a copy: n = n + 10 changes only the local copy (the caller's n stays 1), but v[0] = n writes the local value 11 into the array;
  • v is a copy of the reference to the same array, so the write v[0] = 11 is visible to the caller;
  • w = new int[3] makes the local copy of the reference point to a new array; w[1] = 99 changes the new array only. The caller's array stays {5, 5, 5}.

Output: 1 11 5 5. Typical error: believing that w = new int[3] replaces the caller's array, or that n is modified (Java - ArraysA Java array is an object holding a sequence of elements of the same type (primitive or reference). It is built with new TypeName[length], assigned to a reference variable declared TypeName[] name (no length in the declaration, so the variable can later refer to arrays of any length). Elements start at 0, false or null; they are read and written with name[index], with index from 0 to length - 1; any other index throws ArrayIndexOutOfBoundsException at run time (typical bug: index equal to length, or i <= values.length in a loop). The size is the public final variable length (not a method, cannot be assigned). Elements can be given at once with {2, 3, 5}. Assigning an array variable to another copies only the reference (both see the same array); a real copy needs a new array of the same type and length filled by a loop or by System.arraycopy(from, fromStart, to, toStart, count).Java - Arrays → for arrays as reference variables).

Q6. For each i the inner loop runs 5−i5 - i times: 5+4+3+2+1=155 + 4 + 3 + 2 + 1 = 15. With nn in place of 5 the count is n+(n−1)+⋯+1=n(n+1)/2n + (n-1) + \dots + 1 = n(n+1)/2, which is 500500 for n=1000n = 1000, and grows as n2n^2: quadratic (Computational ComplexityAlgorithms are analysed to predict performance on unseen inputs and to compare solutions of the same problem, mainly in time (also in space). Experimental analysis times an implementation (time.time(), doubling input sizes, T(n) = an^b with b = log2(T(2n)/T(n))) but measures the implementation, not the algorithm. Theoretical analysis counts basic steps under a cost model and classifies the result with asymptotic notation: O is an upper bound, Omega a lower bound, Theta both (f(n) <= cg(n) for all n >= n0). Rules: sum sequential blocks, take the larger branch of an if for an upper bound (the smaller for a lower bound), sum the iterations of a loop. Worked case: reverse a list with a shifting inner loop is Theta(n^2); writing each element directly in its place is Theta(n), and no faster hardware can compensate for the worse class on large inputs.Computational Complexity →). Typical error: answering 25 (a full square) or 10 (starting j at i + 1).

Q7. continue skips the rest of the current iteration of the inner loop, break ends the innermost loop only; the println is executed after the inner loop for every i (Java - Language BasicsJava (Sun Microsystems, 1991) is an object-oriented language designed to be simple and CPU-independent ("write once, run anywhere"). Every program is made of classes; an executable class needs a main method, and the public class name must match the file name (Hello.java). The source is compiled by javac into bytecode (Hello.class), the machine code of the Java Virtual Machine, which the Java interpreter (java Hello) runs, translating on the fly into real CPU instructions; so Java is both compiled and interpreted, portable at source and bytecode level and of intermediate efficiency. Errors are syntax (found by the compiler) or logical (found only by testing). The grammar has five token types (keywords, identifiers, literals, separators, operators). Complements: loop end tests with less-than, sentinel values and the loop and a half, break and continue, the conditional operator and switch.Java - Language Basics →). Trace (the test j == i comes first):

i j values and action printed
1 1 skip; 2 prints 2; 3 prints 3; 4 break 2 3
2 1 prints 2; 2 skip; 3 prints 6; 4 break 2 6
3 1 prints 3; 2 prints 6; 3 skip; 4 break 3 6
4 1 prints 4; 2 prints 8; 3 prints 12; 4 skip (j == i) 4 8 12

For i = 4 the value j = 4 is skipped by continue before the break test is reached. Typical error: thinking break ends the outer loop too, or testing j > 3 before j == i.

Q8. The cycle is the same as in Q2: fetch increases the PC, execute may overwrite it. JNZ is a conditional jump: the execute step writes the target address into the PC only if R1 is not zero, otherwise the PC keeps the value already incremented by the fetch (Computer ArchitectureModern computers follow the von Neumann model: a CPU (ALU, control unit, registers, cache) driven by a clock runs a fetch-decode-execute cycle on programs and data stored in the same memory; memory is a hierarchy from fast, small and volatile (registers, cache, RAM) to slow, large and persistent (SSD, disk, tape); CPU, memory and I/O talk through a bus made of data, address and control lines on the motherboard.Computer Architecture →, Programming FundamentalsThe CPU only executes machine instructions (opcodes) of its own instruction set; assembly languages give them mnemonic names and an assembler translates them one-to-one, but they are CPU specific; high-level languages are CPU independent and are translated by a compiler (executable code is CPU specific) or run by an interpreter; compiled languages are generally more efficient, interpreted languages more portable, and Java aims at both.Programming Fundamentals →). Trace of the loop (addresses 2, 3, 4):

pass R2 after address 2 R1 after address 3 JNZ at address 4 PC after execute
1 0+3=30 + 3 = 3 2 R1≠0R1 \neq 0: jump 2
2 3+2=53 + 2 = 5 1 R1≠0R1 \neq 0: jump 2
3 5+1=65 + 1 = 6 0 R1=0R1 = 0: no jump 5

a) R2 =3+2+1=6= 3 + 2 + 1 = 6, which STORE R2 writes to memory. b) Addresses 0 and 1 run once (2 instructions), the loop body (addresses 2, 3, 4) runs 3 times (9 instructions), then addresses 5 and 6 (2 instructions): 2+9+2=132 + 9 + 2 = 13. c) After the fetch of the instruction at address 4 the PC is already 5; the first execution of JNZ replaces it with 2, the last one (with R1 = 0) leaves it at 5, and the program falls through to STORE. Typical errors: counting only 7 instructions (the addresses, not the executions), stopping the loop one pass early or late, or thinking the jump is always taken.

Exercise 2 (points 10)

Binary search in a sorted array. An array int[] a of length nn is sorted in non-decreasing order and may contain repeated values. Constraints: 0≤n≤1050 \le n \le 10^5, every value and every parameter is in [−109,109][-10^9, 10^9]. In all methods the time must be O(log⁡n)O(\log n) and the extra space O(1)O(1): no copy of the array and no linear scan. Write, as static methods of a class SortedArrays:

a) (5 points) static int insertionPoint(int[] a, int x): the smallest index i such that a[i] >= x, or a.length if no such element exists. (It is the position where x can be inserted so that the array stays sorted, before any equal elements.)

b) (2 points) static int firstOccurrence(int[] a, int x): the index of the first element equal to x, or −1-1 if x is not in the array.

c) (3 points) static int countInRange(int[] a, int lo, int hi): the number of elements e with lo <= e <= hi (with lo <= hi).

Examples, with a = {1, 3, 3, 3, 7, 9}:

call returns
insertionPoint(a, 3) 1
insertionPoint(a, 4) 4
insertionPoint(a, 10) 6
firstOccurrence(a, 3) 1
firstOccurrence(a, 7) 4
firstOccurrence(a, 4) -1
countInRange(a, 3, 7) 4
countInRange(a, 4, 6) 0
countInRange(a, -5, 100) 6

Finally, write the recurrence for the time of the search on an array of size nn and solve it by successive substitution.

Show the result
  • Examples as in the table above; also insertionPoint(a, 0) =0= 0 and firstOccurrence on an empty array =−1= -1.
  • Complexity of all three methods: O(log⁡n)O(\log n) time (countInRange makes two searches), O(1)O(1) extra space.
  • Recurrence: T(n)=T(n/2)+1T(n) = T(n/2) + 1 with T(1)=1T(1) = 1, so T(n)=1+log⁡2nT(n) = 1 + \log_2 n for nn a power of 2, i.e. Θ(log⁡n)\Theta(\log n).
Show the full solution

Idea. The three tasks are the same search. Keep the half-open interval [lo, hi) of the positions where the answer can still be, with the invariant: every element before lo is < x, every element from hi onward is >= x. At each step look at the middle: if a[mid] < x, the answer is to its right (lo = mid + 1); otherwise a[mid] >= x, so mid itself may be the answer and hi = mid. The interval is empty when lo == hi, and the invariant says that this is exactly the smallest index with a[i] >= x (Searching and Sorting AlgorithmsLinear search scans left to right and returns the index of the first occurrence or -1 (worst and average case O(n), works on any list). Binary search needs a SORTED list: it compares with the middle element and keeps one half, so T(n) = T(n/2) + 1, i.e. O(log n) (recursive, two base cases: empty interval -> -1, element found; tail recursive, so a loop version exists). Finding max/min always reads all n elements: Theta(n). Sorting: selection sort (find the minimum of the unsorted part, swap it in place) is always O(n^2), T(n) = n^2/2 + 9n/2 - 5 counting list accesses; insertion sort (insert the next element into the sorted left part by shifting) costs O(n) on sorted data and O(n^2) in the average and worst case; MergeSort (split, sort both halves recursively, merge) has T(n) = 2T(n/2) + 5n, i.e. O(n log n), at the price of extra memory. Recurrences are solved by successive substitution; general form T(n) = aT(n/b) + f(n) (Master Theorem). Not every recursion is efficient: naive recursive Fibonacci, T(n) = T(n-1) + T(n-2) + 1, is exponential (about phi^n calls), while the iterative version is O(n).Searching and Sorting Algorithms →). Because the test uses < and does not stop at an equal element, the search keeps going left and ends on the first occurrence, which is what a plain binary search does not guarantee.

Trace of insertionPoint(a, 4) on {1, 3, 3, 3, 7, 9}:

lo hi mid a[mid] action
0 6 3 3 3<43 < 4: lo = 4
4 6 5 9 9≥49 \ge 4: hi = 5
4 5 4 7 7≥47 \ge 4: hi = 4
4 4 empty: return 4

For x = 3: lo = 0, hi = 6 gives mid = 3 (a[3] = 3, not < 3, so hi = 3), then mid = 1 (hi = 1), then mid = 0 (a[0] = 1 < 3, so lo = 1): returns 1, the first 3.

firstOccurrence. Let i = insertionPoint(a, x). If i < a.length and a[i] == x, then i is the first occurrence (everything before is < x); otherwise x is absent. countInRange. The elements >= lo start at insertionPoint(a, lo); the elements > hi, that is >= hi + 1 (integers), start at insertionPoint(a, hi + 1). The count is the difference of the two positions. The constraint ∣hi∣≤109|hi| \le 10^9 guarantees that hi + 1 does not overflow an int (Representation of InformationEverything in a computer is a sequence of bits, so each kind of information needs a coding. Natural numbers use positional notation in base 2 (conversion by repeated division by 2); signed integers use two's complement (range from minus 2 to the n minus 1 up to 2 to the n minus 1, minus 1), where negation is invert-all-bits-and-add-1, sums are plain binary sums and overflow is detected on the two top carries; hexadecimal groups bits in fours; fractions use fixed point or IEEE 754 floating point (sign, exponent in excess 127, 23-bit fraction) and are only approximate; characters are unsigned integers in a code table (ASCII, Unicode); images, video and sound are stored as numbers too (pixels, frame differences, samples).Representation of Information →; with hi = Integer.MAX_VALUE the sum would wrap to a negative value and the result would be wrong).

java
public class SortedArrays {
    // smallest i with a[i] >= x, or a.length: invariant a[0..lo-1] < x, a[hi..n-1] >= x
    static int insertionPoint(int[] a, int x) {
        int lo = 0, hi = a.length;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;      // no overflow even for huge arrays
            if (a[mid] < x) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }

    static int firstOccurrence(int[] a, int x) {
        int i = insertionPoint(a, x);
        return (i < a.length && a[i] == x) ? i : -1;
    }

    static int countInRange(int[] a, int lo, int hi) {
        return insertionPoint(a, hi + 1) - insertionPoint(a, lo);
    }

    public static void main(String[] args) {
        int[] a = {1, 3, 3, 3, 7, 9};
        System.out.println(insertionPoint(a, 3) + " " + insertionPoint(a, 4) + " " + insertionPoint(a, 10));
        System.out.println(firstOccurrence(a, 3) + " " + firstOccurrence(a, 7) + " " + firstOccurrence(a, 4));
        System.out.println(countInRange(a, 3, 7) + " " + countInRange(a, 4, 6) + " " + countInRange(a, -5, 100));
    }
}

The program prints:

1 4 6
1 4 -1
4 0 6

Tests run. Besides the examples (also insertionPoint(a, 0) = 0, firstOccurrence(new int[0], 5) = -1, countInRange(a, 3, 3) = 3), the three methods were compared with the obvious linear scans on 20000 random sorted arrays with up to 11 elements and many repeated values, with no difference.

Complexity. Each iteration looks at one element and halves the interval, so on nn elements T(n)=T(n/2)+1,T(1)=1.T(n) = T(n/2) + 1,\qquad T(1) = 1. By successive substitution T(n)=T(n/2k)+kT(n) = T(n/2^k) + k; the base case is reached when n/2k=1n/2^k = 1, i.e. k=log⁡2nk = \log_2 n, so T(n)=1+log⁡2n∈Θ(log⁡n)T(n) = 1 + \log_2 n \in \Theta(\log n) (Computational ComplexityAlgorithms are analysed to predict performance on unseen inputs and to compare solutions of the same problem, mainly in time (also in space). Experimental analysis times an implementation (time.time(), doubling input sizes, T(n) = an^b with b = log2(T(2n)/T(n))) but measures the implementation, not the algorithm. Theoretical analysis counts basic steps under a cost model and classifies the result with asymptotic notation: O is an upper bound, Omega a lower bound, Theta both (f(n) <= cg(n) for all n >= n0). Rules: sum sequential blocks, take the larger branch of an if for an upper bound (the smaller for a lower bound), sum the iterations of a loop. Worked case: reverse a list with a shifting inner loop is Theta(n^2); writing each element directly in its place is Theta(n), and no faster hardware can compensate for the worse class on large inputs.Computational Complexity →). For n=105n = 10^5 this is at most 17 iterations, against 10510^5 of a linear scan. The loop version uses constant space (a recursive version would use O(log⁡n)O(\log n) stack, see RecursionA function is recursive when it calls itself; it is correct only if it has at least one base case that needs no recursive call and if every recursive call works on a simpler problem that gets closer to a base case (otherwise Python stops with RecursionError, the limit being 1000 nested calls). Each pending call is a record on the call stack. Types: linear (one call, e.g. factorial), binary (two calls, e.g. sum of a list by halves), tail (the call is the last action, solved with an accumulator and easy to turn into a loop), multiple (fib_bad recomputes the same values and explodes). Typical examples: factorial, Fibonacci, reversing a string, Towers of Hanoi (2^n - 1 moves). Recursion is elegant for naturally recursive problems but usually less efficient than a loop.Recursion →). countInRange runs two searches: 2log⁡2n+O(1)2\log_2 n + O(1), still O(log⁡n)O(\log n).

Typical errors.

  • Returning as soon as a[mid] == x: this finds an occurrence, not the first one, and does not give the insertion point when x is absent.
  • hi = mid - 1 (or lo = mid) with the half-open interval: the loop may skip the answer or never end. Check which interval convention the invariant uses.
  • Writing a[hi] or a[mid] with hi = a.length without checking: ArrayIndexOutOfBoundsException (insertionPoint never reads a[a.length], but firstOccurrence must test i < a.length before a[i]).
  • Counting by a linear scan: correct but O(n)O(n), not accepted by the required complexity.
  • Using binary search on an unsorted array.

Exercise 3 (points 12)

Recursion. Write the methods below as static methods using recursion (no loops in the recursive part), and for each one give the recurrence of the cost and its solution.

a) (4 points) static long power(long x, int n): returns xnx^n for n≥0n \ge 0 (with x0=1x^0 = 1), using O(log⁡n)O(\log n) multiplications. You may assume that the result fits in a long. Examples: power(2, 10) =1024= 1024, power(3, 13) =1594323= 1594323, power(-2, 7) =−128= -128, power(5, 0) =1= 1. How many calls of power are made by power(1, 1000), counting the first?

b) (3 points) static boolean isPalindrome(int[] a, int i, int j): returns true if the elements a[i], ..., a[j] read the same from left to right and from right to left (an empty or one-element range is a palindrome). The first call for a whole array is isPalindrome(a, 0, a.length - 1). Examples: {1, 2, 3, 2, 1} gives true, {4, 7, 7, 4} gives true, {1, 2, 3} gives false, the empty array gives true.

c) (5 points) static void binaryStrings(int n): prints all the binary strings of length nn (0≤n≤200 \le n \le 20), one per line, in increasing alphabetical order. Examples: binaryStrings(1) prints 0 and 1; binaryStrings(2) prints 00, 01, 10, 11; binaryStrings(3) prints the 8 strings from 000 to 111; binaryStrings(0) prints one empty line. How many recursive calls are made for a given nn, and what is the total cost?

Show the result
  • a) 1024, 1594323, -128, 1. power(1, 1000) makes 11 calls (values of nn: 1000, 500, 250, 125, 62, 31, 15, 7, 3, 1, 0). Recurrence T(n)=T(⌊n/2⌋)+cT(n) = T(\lfloor n/2 \rfloor) + c, so T(n)∈Θ(log⁡n)T(n) \in \Theta(\log n) (the naive x⋅xn−1x \cdot x^{n-1} is Θ(n)\Theta(n)).
  • b) true, true, false, true. Recurrence T(n)=T(n−2)+cT(n) = T(n-2) + c, so Θ(n)\Theta(n) time in the worst case, and a stack depth of about n/2n/2.
  • c) Output for n=3n = 3: 000, 001, 010, 011, 100, 101, 110, 111. Number of calls C(n)=2C(n−1)+1C(n) = 2C(n-1) + 1 with C(0)=1C(0) = 1, so C(n)=2n+1−1C(n) = 2^{n+1} - 1; total cost Θ(n 2n)\Theta(n \, 2^n) (there are 2n2^n strings of nn characters, so it cannot be less).
Show the full solution

a) Fast power. Idea: xn=(xn/2)2x^n = (x^{n/2})^2 if nn is even and xn=x (x⌊n/2⌋)2x^n = x\,(x^{\lfloor n/2 \rfloor})^2 if nn is odd. Base case: n=0n = 0 returns 1. Recursive step: the problem size passes from nn to ⌊n/2⌋\lfloor n/2 \rfloor, which is smaller and tends to the base case (RecursionA function is recursive when it calls itself; it is correct only if it has at least one base case that needs no recursive call and if every recursive call works on a simpler problem that gets closer to a base case (otherwise Python stops with RecursionError, the limit being 1000 nested calls). Each pending call is a record on the call stack. Types: linear (one call, e.g. factorial), binary (two calls, e.g. sum of a list by halves), tail (the call is the last action, solved with an accumulator and easy to turn into a loop), multiple (fib_bad recomputes the same values and explodes). Typical examples: factorial, Fibonacci, reversing a string, Towers of Hanoi (2^n - 1 moves). Recursion is elegant for naturally recursive problems but usually less efficient than a loop.Recursion →). The key point is to call power once, store the result in a variable and square it: calling power(x, n/2) * power(x, n/2) makes two calls on the same argument (the same mistake as fib_bad).

java
public class Recursion {
    static int calls = 0;                       // only to count the calls

    static long power(long x, int n) {
        calls++;
        if (n == 0) return 1;                   // base case
        long h = power(x, n / 2);               // ONE recursive call
        return (n % 2 == 0) ? h * h : x * h * h;
    }

    static boolean isPalindrome(int[] a, int i, int j) {
        if (i >= j) return true;                // base case: empty or one element
        if (a[i] != a[j]) return false;         // base case: mismatch
        return isPalindrome(a, i + 1, j - 1);   // smaller range, tail recursion
    }

    static void gen(String prefix, int n) {
        if (n == 0) {                           // base case: the string is complete
            System.out.println(prefix);
            return;
        }
        gen(prefix + "0", n - 1);               // all strings starting with prefix + "0"
        gen(prefix + "1", n - 1);               // then all those starting with prefix + "1"
    }

    static void binaryStrings(int n) {
        gen("", n);
    }

    public static void main(String[] args) {
        System.out.println(power(2, 10) + " " + power(3, 13) + " " + power(-2, 7) + " " + power(5, 0));
        calls = 0;
        power(1, 1000);
        System.out.println("calls: " + calls);

        int[][] tests = {{1, 2, 3, 2, 1}, {4, 7, 7, 4}, {1, 2, 3}, {}};
        for (int[] t : tests)
            System.out.print(isPalindrome(t, 0, t.length - 1) + " ");
        System.out.println();

        binaryStrings(2);
    }
}

The program prints:

1024 1594323 -128 1
calls: 11
true true false true 
00
01
10
11

Calls of power(1, 1000): the argument nn goes through 1000, 500, 250, 125, 62, 31, 15, 7, 3, 1, 0: 10 calls with n≥1n \ge 1 plus the base case, 11 in total (in general ⌊log⁡2n⌋+2\lfloor \log_2 n \rfloor + 2). The overflow: the constraint says that xnx^n fits in a long; the intermediate values h⋅hh \cdot h are at most ∣xn∣|x^n| in absolute value, so no wrong wrap-around occurs (Representation of InformationEverything in a computer is a sequence of bits, so each kind of information needs a coding. Natural numbers use positional notation in base 2 (conversion by repeated division by 2); signed integers use two's complement (range from minus 2 to the n minus 1 up to 2 to the n minus 1, minus 1), where negation is invert-all-bits-and-add-1, sums are plain binary sums and overflow is detected on the two top carries; hexadecimal groups bits in fours; fractions use fixed point or IEEE 754 floating point (sign, exponent in excess 127, 23-bit fraction) and are only approximate; characters are unsigned integers in a code table (ASCII, Unicode); images, video and sound are stored as numbers too (pixels, frame differences, samples).Representation of Information →).

Recurrence of a). Each call does a constant amount of work cc (one or two multiplications, one test) and then one call on half the size: T(n)=T(⌊n/2⌋)+c,T(0)=c.T(n) = T(\lfloor n/2 \rfloor) + c,\qquad T(0) = c. Successive substitution: T(n)=T(n/2k)+kcT(n) = T(n/2^k) + kc, and the base case is reached after about k=log⁡2nk = \log_2 n steps, so T(n)∈Θ(log⁡n)T(n) \in \Theta(\log n) (Searching and Sorting AlgorithmsLinear search scans left to right and returns the index of the first occurrence or -1 (worst and average case O(n), works on any list). Binary search needs a SORTED list: it compares with the middle element and keeps one half, so T(n) = T(n/2) + 1, i.e. O(log n) (recursive, two base cases: empty interval -> -1, element found; tail recursive, so a loop version exists). Finding max/min always reads all n elements: Theta(n). Sorting: selection sort (find the minimum of the unsorted part, swap it in place) is always O(n^2), T(n) = n^2/2 + 9n/2 - 5 counting list accesses; insertion sort (insert the next element into the sorted left part by shifting) costs O(n) on sorted data and O(n^2) in the average and worst case; MergeSort (split, sort both halves recursively, merge) has T(n) = 2T(n/2) + 5n, i.e. O(n log n), at the price of extra memory. Recurrences are solved by successive substitution; general form T(n) = aT(n/b) + f(n) (Master Theorem). Not every recursion is efficient: naive recursive Fibonacci, T(n) = T(n-1) + T(n-2) + 1, is exponential (about phi^n calls), while the iterative version is O(n).Searching and Sorting Algorithms → solves the same recurrence for binary search). The naive version x⋅power(x,n−1)x \cdot \text{power}(x, n-1) has T(n)=T(n−1)+c=Θ(n)T(n) = T(n-1) + c = \Theta(n), and the version with two calls T(n)=2T(n/2)+cT(n) = 2T(n/2) + c is also Θ(n)\Theta(n): no gain.

b) Palindrome. Base cases: i≥ji \ge j (empty or one element: true) and a[i] != a[j] (false). Step: the two extremes are equal, so the answer is that of the inner range a[i+1..j-1], two elements shorter. The call is the last action: a tail recursion, easy to turn into a loop (RecursionA function is recursive when it calls itself; it is correct only if it has at least one base case that needs no recursive call and if every recursive call works on a simpler problem that gets closer to a base case (otherwise Python stops with RecursionError, the limit being 1000 nested calls). Each pending call is a record on the call stack. Types: linear (one call, e.g. factorial), binary (two calls, e.g. sum of a list by halves), tail (the call is the last action, solved with an accumulator and easy to turn into a loop), multiple (fib_bad recomputes the same values and explodes). Typical examples: factorial, Fibonacci, reversing a string, Towers of Hanoi (2^n - 1 moves). Recursion is elegant for naturally recursive problems but usually less efficient than a loop.Recursion →). Trace for {1, 2, 3, 2, 1}: (0, 4): 1=11 = 1, go on; (1, 3): 2=22 = 2, go on; (2, 2): i≥ji \ge j, true.

Recurrence of b). In the worst case (a palindrome) T(n)=T(n−2)+cT(n) = T(n-2) + c, with T(0)=T(1)=cT(0) = T(1) = c. Substitution: T(n)=T(n−2k)+kcT(n) = T(n-2k) + kc, and the base case after k≈n/2k \approx n/2 steps: T(n)∈Θ(n)T(n) \in \Theta(n); the best case (extremes different) is O(1)O(1). The depth of the call stack is about n/2n/2, so the extra space is O(n)O(n) unlike the loop version (O(1)O(1)); for very long arrays a loop is better (RecursionA function is recursive when it calls itself; it is correct only if it has at least one base case that needs no recursive call and if every recursive call works on a simpler problem that gets closer to a base case (otherwise Python stops with RecursionError, the limit being 1000 nested calls). Each pending call is a record on the call stack. Types: linear (one call, e.g. factorial), binary (two calls, e.g. sum of a list by halves), tail (the call is the last action, solved with an accumulator and easy to turn into a loop), multiple (fib_bad recomputes the same values and explodes). Typical examples: factorial, Fibonacci, reversing a string, Towers of Hanoi (2^n - 1 moves). Recursion is elegant for naturally recursive problems but usually less efficient than a loop.Recursion →, section on when to use recursion).

c) All binary strings. To print all strings of length nn we build them one character at a time: gen(prefix, n) prints all the strings that start with prefix and have nn more characters. Base case: n=0n = 0, prefix is complete: print it. Step: all the strings with prefix prefix are those starting with prefix + "0" (first) and those starting with prefix + "1" (then): two recursive calls on size n−1n-1. Calling the "0" branch first gives the alphabetical order. This is a binary recursion whose call tree is complete, like the Towers of Hanoi with 2n−12^n - 1 moves (RecursionA function is recursive when it calls itself; it is correct only if it has at least one base case that needs no recursive call and if every recursive call works on a simpler problem that gets closer to a base case (otherwise Python stops with RecursionError, the limit being 1000 nested calls). Each pending call is a record on the call stack. Types: linear (one call, e.g. factorial), binary (two calls, e.g. sum of a list by halves), tail (the call is the last action, solved with an accumulator and easy to turn into a loop), multiple (fib_bad recomputes the same values and explodes). Typical examples: factorial, Fibonacci, reversing a string, Towers of Hanoi (2^n - 1 moves). Recursion is elegant for naturally recursive problems but usually less efficient than a loop.Recursion →). The + between a string and a literal builds a new string (Java - Language BasicsJava (Sun Microsystems, 1991) is an object-oriented language designed to be simple and CPU-independent ("write once, run anywhere"). Every program is made of classes; an executable class needs a main method, and the public class name must match the file name (Hello.java). The source is compiled by javac into bytecode (Hello.class), the machine code of the Java Virtual Machine, which the Java interpreter (java Hello) runs, translating on the fly into real CPU instructions; so Java is both compiled and interpreted, portable at source and bytecode level and of intermediate efficiency. Errors are syntax (found by the compiler) or logical (found only by testing). The grammar has five token types (keywords, identifiers, literals, separators, operators). Complements: loop end tests with less-than, sentinel values and the loop and a half, break and continue, the conditional operator and switch.Java - Language Basics →).

Recurrence of c). Number of calls: C(n)=2C(n−1)+1C(n) = 2C(n-1) + 1, C(0)=1C(0) = 1. Substitution: C(n)=2C(n−1)+1=4C(n−2)+3=8C(n−3)+7=⋯=2kC(n−k)+2k−1C(n) = 2C(n-1) + 1 = 4C(n-2) + 3 = 8C(n-3) + 7 = \dots = 2^k C(n-k) + 2^k - 1; for k=nk = n: C(n)=2n+2n−1=2n+1−1C(n) = 2^n + 2^n - 1 = 2^{n+1} - 1 (for n=10n = 10 a test counted 2047 calls). The call at depth kk builds a string of kk characters, so the total cost is ∑k=0n2k⋅k=Θ(n 2n)\sum_{k=0}^{n} 2^k \cdot k = \Theta(n \, 2^n), which is also the size of the output: 2n2^n lines of nn characters. The cost is exponential and no algorithm can do better, since the output itself is exponential.

Tests run. The three methods were compared with the direct definitions on random data: power with a loop for 2000 pairs (base between −3-3 and 33, exponent up to 29), isPalindrome with a comparison of the array with its reverse for 5000 random 0/1 arrays of length up to 8, and binaryStrings for n=0n = 0 (one empty line), n=2n = 2 and n=3n = 3 (eight strings in order).

Typical errors.

  • In power, calling the recursion twice (power(x, n/2) * power(x, n/2)): the cost goes back to Θ(n)\Theta(n).
  • Forgetting the odd case (x * h * h) or using n / 2 for odd nn without the extra factor xx.
  • A missing base case or a step that does not shrink the problem: StackOverflowError.
  • In isPalindrome, a base case only for i == j: for an even number of elements the indices cross (i > j) and the recursion goes on until an index error. Use i >= j.
  • In gen, printing at the wrong moment (before the string is complete), or changing a shared string instead of passing a new one (strings are built with +, so each call has its own prefix).
  • Giving the cost of c) as O(2n)O(2^n) without the factor nn for the length of each string, or saying that the number of calls is 2n2^n (it is 2n+1−12^{n+1} - 1).
Self-assessment grid
exercise points what is needed for full points typical errors
1 (Q1-Q8) 8 b); PC 3, 5 and 5 executed instructions; 0.25 ns and 147 483 648 bytes of difference; −2147483648-2147483648, −2-2, −2147483648-2147483648; 1 11 5 5; 15, 500500, quadratic; the four lines of Q7; R2 = 6, 13 instructions, PC 2 then 5 PC not yet incremented; GiB equal to GB; thinking -b is positive; believing w = new int[3] changes the caller's array; counting a full square of iterations; break leaving both loops; counting addresses instead of executions; jump always taken
2a 5 half-open interval [lo, hi), invariant stated, a[mid] < x gives lo = mid + 1, else hi = mid, returns lo, no early stop on equality stopping at a[mid] == x; hi = mid - 1 with the half-open interval; infinite loop
2b 2 insertionPoint, then test i < a.length && a[i] == x reading a[i] without the bound test; returning any occurrence
2c 3 ip(hi+1)−ip(lo)\text{ip}(hi+1) - \text{ip}(lo), with the reason for hi+1hi + 1 (integers) and for no overflow; O(log⁡n)O(\log n) linear scan; insertionPoint(hi) (excludes the elements equal to hi)
2 recurrence included T(n)=T(n/2)+1T(n) = T(n/2) + 1, successive substitution, Θ(log⁡n)\Theta(\log n) missing base case T(1)T(1); O(n)O(n) stated
3a 4 one recursive call stored in a variable, even and odd case, base case n=0n = 0, 11 calls, T(n)=T(n/2)+cT(n) = T(n/2) + c, Θ(log⁡n)\Theta(\log n) two calls to power; odd case forgotten; cost Θ(n)\Theta(n)
3b 3 base cases i >= j and mismatch, step (i + 1, j - 1), T(n)=T(n−2)+cT(n) = T(n-2) + c, Θ(n)\Theta(n) i == j only; step (i + 1, j)
3c 5 base case n=0n = 0 prints, two calls with "0" then "1", order correct, C(n)=2C(n−1)+1C(n) = 2C(n-1) + 1, 2n+1−12^{n+1} - 1 calls, Θ(n 2n)\Theta(n\,2^n) wrong order; printing too early; forgetting the factor nn; 2n2^n calls instead of 2n+1−12^{n+1} - 1