25-Comp-A4 Program Design and Data Structures · December 2017
Question 2 of 9: Programming — Hailstone (Collatz) Sequence
Nivaar worked solution (AI-drafted; not reviewed by a licensed engineer) · Last updated
Notes on this paper
Pseudocode or any high-level language is
accepted, and the examiner's note states explicitly that marking emphasises
the operation of the program, not syntactic details.
Reference texts for this subject.
Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms,
4th ed. — tree traversals and BSTs (ch. 12), recursion and
divide-and-conquer (ch. 2, 4), asymptotic analysis (ch. 3).
Weiss, Data Structures and Algorithm Analysis in C, 2nd ed. —
linked lists and stacks (ch. 3), binary trees (ch. 4).
Deitel & Deitel, C++ How to Program, 10th ed. — class
design and operator overloading (ch. 9–11), file streams (ch. 14).
Kernighan & Ritchie, The C Programming Language, 2nd ed. —
arrays and file I/O (ch. 1, 7), pointers, structures and linked
lists (ch. 5–6).
Stroustrup, The C++ Programming Language, 4th ed. — class
templates and value semantics (ch. 3, 25–27).
The Computer Engineering citation list is built around architecture and
networking texts (Patterson & Hennessy, Tanenbaum, Mano); this subject is
programming and data structures, so the works above are cited instead.
Given. Starting integer $n_0>0$; rule $n_{k+1}=3n_k+1$
(odd) or $n_{k+1}=n_k/2$ (even); worked example $n_0=10\Rightarrow$ 6 steps,
largest value 16.
Find. A program reporting the step count to reach the
repeating ground state $4,2,1,4,2,1,\ldots$ and the largest value visited.
Approach. Apply the rule repeatedly, counting one step
per application and tracking the running maximum, stopping the first time
the current value reaches 1 (the ground state $4,2,1$ then repeats forever
from there, so reaching 1 marks the end of the "climbing" part of the
sequence — this matches the worked example exactly).
Confirm the stopping rule against the worked example.
For $n_0=10$: $10\to5\to16\to8\to4\to2\to1$ is 6 applications of the rule,
and the running maximum along the way is 16 — both figures match the
question's own example, so "reach the ground state" means "reach the value
1" (after which $4,2,1$ repeats forever from the next steps).
Write the program.
#include <stdio.h>
int main(void)
{
long n, largest, steps = 0;
printf("Enter a starting number: ");
scanf("%ld", &n);
largest = n;
while (n != 1) {
if (n % 2 == 1)
n = 3 * n + 1;
else
n = n / 2;
steps++;
if (n > largest) largest = n;
}
printf("Steps to reach the ground state: %ld\n", steps);
printf("Largest number reached: %ld\n", largest);
return 0;
}
Verify the trace. The program's loop body executes for
$n_0=10$ exactly at $n=10,5,16,8,4,2$ (6 iterations, ending when $n$ becomes
1), and $\max\{10,5,16,8,4,2,1\}=16$.
$$\boxed{\text{steps}=6,\ \ \text{largest}=16}$$