7.03a–7.03d - Defining, tracing and timing algorithms

7.03a–7.03d - Defining, tracing and timing algorithms

An algorithm turns a problem into instructions that another person or a computer can follow. You will recognise its essential properties, trace and adapt short instructions, judge their uses and limitations, and estimate how running time grows when the problem gets larger.

What makes an algorithm

A machine takes 0.080.08 seconds to process 400400 records. How long should it need for 12001200 records: three times as long, nine times as long, or something else? You cannot answer from the record count alone. You need to know what the instructions do.

Start with a smaller problem: find the largest number in the list 8,3,11,58, 3, 11, 5. Keep 88 as the current largest; compare it with 33, then 1111, then 55, updating when a larger value appears. The successive current largest values are 8,8,11,118, 8, 11, 11. The final output is 1111.

Algorithm

An algorithm is a finite sequence of unambiguous instructions with an input and an output. It is deterministic: a given input, together with the stated rules, determines what happens at every step. It must finish after finitely many steps for every permitted input.

The input above is the list; the output is its largest value. “Find a large-looking number” is not a complete instruction: two people could make different choices. “Compare the next entry with the current largest and replace the current largest if it is smaller” specifies the choice.

A counter records how many times something has happened. For a list of length nn, a counter can start at 22, identify the next position to inspect and increase by 11 each time. A stopping condition tells the procedure when to finish: stop when that counter exceeds nn. These meanings are not in the formula booklet: learn them.

A finite-looking description need not describe a terminating process. “Start at 11, add 22 repeatedly, stop at 1010” never stops: it visits only odd integers. Changing the stopping condition to “stop when the value is at least 1010” makes it finish at 1111. The permitted input and the exact stopping test both matter.

Key idea

An algorithm needs a definite next action and a guaranteed finish, as well as a sensible answer when it finishes.

Check the stopping condition rather than judging the instructions by their length.

Tracing assignments and repeated steps

A trace follows the instructions in order, recording values as they change instead of trying to guess the final answer.

The assignment x←x+1x\leftarrow x+1 means “replace the stored value of xx by its old value plus 11”. It is an instruction, not an equation claiming that a number equals itself plus 11. Later lines use the updated value.

INT and ABS

ABS⁡(x)=∣x∣\operatorname{ABS}(x)=|x| is the non-negative magnitude of xx. For non-negative xx, INT⁡(x)\operatorname{INT}(x) gives the integer part, discarding the fractional part. For example, ABS⁡(−23)=23\operatorname{ABS}(-23)=23 and INT⁡(23/10)=2\operatorname{INT}(23/10)=2. Every use of INT⁡\operatorname{INT} in this lesson has a non-negative argument.

These function meanings are not in the formula booklet: learn them. The following algorithm adds the decimal digits of an integer input NN. It handles a negative input by first taking its magnitude.

StepInstruction
11Input an integer NN; set x←ABS⁡(N)x\leftarrow\operatorname{ABS}(N) and s←0s\leftarrow0
22If x=0x=0, output ss and stop
33Set q←INT⁡(x/10)q\leftarrow\operatorname{INT}(x/10)
44Set d←x−10qd\leftarrow x-10q, then s←s+ds\leftarrow s+d
55Set x←qx\leftarrow q, then return to step 22

For instance, 284=10(28)+4284=10(28)+4: qq keeps the earlier digits and dd extracts the final digit. Replacing xx by qq removes that digit, so positive xx decreases until it becomes 00. The flow diagram presents exactly the same instructions; a decision diamond has separate yes and no exits.

[DIAGRAM: asset_name: A digit sum algorithm; asset_slug: h245_7_03_digit_flow; caption: The loop extracts one final digit, adds it to the total and removes it before testing again; description: A flow diagram begins with integer input N and initialisation x equals ABS(N), s equals zero. A diamond asks whether x equals zero. The yes branch outputs s and stops. The no branch sets q to INT(x divided by ten), d to x minus ten q, s to s plus d, and x to q, then returns to the decision diamond. Arrows show the order of assignments.]
The loop extracts one final digit, adds it to the total and removes it before testing again

Worked example 1: a digit-by-digit trace

Question. Trace the algorithm for N=284N=284, and state its output.

Plan. Record xx at the start of each loop and use it to calculate qq, dd and the updated total ss.

Starting xxq=INT⁡(x/10)q=\operatorname{INT}(x/10)d=x−10qd=x-10qUpdated ss
28428428284444
282822881212
2200221414

After the third row, x←0x\leftarrow0, so the next stopping test is true.

Why this step? Calculate dd before replacing xx by qq; otherwise the digit being removed is lost before you use it.

Answer. The output is 1414, the digit sum of 284284.

Check. 2+8+4=142+8+4=14.

Worked example 2 changes only the input to a negative integer containing a zero. The absolute value handles the sign; the zero digit still requires a loop.

Worked example 2: a zero digit

Question. Trace the algorithm for N=−507N=-507, and state its output.

Plan. Initialise x=507x=507, then apply the same assignments in their stated order.

Starting xxqqddUpdated ss
50750750507777
5050550077
5500551212

The next starting value is 00, so the algorithm stops.

Why this step? A zero digit leaves ss unchanged but still removes one decimal place from xx. An unchanged total is not the stopping condition.

Answer. The output is 1212.

Check. 5+0+7=125+0+7=12; the negative sign is not a digit. For input 00, step 22 would immediately output 00, which is also correct.

The same variable can have several values during a trace, but each row must correspond to the same point in the loop.

Watch out

Wrong: stop when ss does not change. A zero digit can leave ss unchanged while earlier digits remain. Right: test the specified condition x=0x=0.

For the next input, retain the row containing its zero digit.

Adapting instructions for a new output

To alter an algorithm, identify which instructions extract information, which combine it and which guarantee that the process stops.

In the digit algorithm, qq and dd extract a digit, s←s+ds\leftarrow s+d combines it with the total, and x←qx\leftarrow q makes progress towards stopping. Changing the output task need not change all three jobs.

Worked example 3: adding squared digits

Question. Adapt the digit-sum algorithm to output the sum of the squares of the digits of an integer. Trace the altered total for input N=312N=312.

Plan. Keep the digit extraction and stopping condition; replace the accumulation instruction by s←s+d2s\leftarrow s+d^2.

d=2:s=0+22=4first extracted digitd=1:s=4+12=5next digitd=3:s=5+32=14last digit\begin{aligned} d=2&:\quad s=0+2^2=4 && \text{first extracted digit}\\ d=1&:\quad s=4+1^2=5 && \text{next digit}\\ d=3&:\quad s=5+3^2=14 && \text{last digit} \end{aligned}

Why this step? Squaring dd before adding gives a sum of squares; squaring the final total would give the square of a sum instead.

Answer. Replace s←s+ds\leftarrow s+d by s←s+d2s\leftarrow s+d^2. The output is 1414.

Check. 32+12+22=143^2+1^2+2^2=14, whereas (3+1+2)2=36(3+1+2)^2=36.

Worked example 4 changes only the quantity accumulated: count digits rather than adding their squares. A counter increases once per extracted digit, regardless of its value.

Worked example 4: counting digits

Question. Adapt the algorithm to output the number of decimal digits of ∣N∣|N|, including the convention that 00 has one digit. Trace it for N=406N=406.

Plan. Deal with zero separately, then count one removal per loop for a non-zero input.

Use these complete instructions:

  1. Input an integer NN; set x←ABS⁡(N)x\leftarrow\operatorname{ABS}(N).
  2. If x=0x=0, output 11 and stop. Otherwise set c←0c\leftarrow0.
  3. Set x←INT⁡(x/10)x\leftarrow\operatorname{INT}(x/10), then c←c+1c\leftarrow c+1.
  4. If x>0x>0, return to step 33; otherwise output cc and stop.
(x,c)=(406,0)initialise⟶(40,1)remove 6⟶(4,2)remove 0⟶(0,3)remove 4\begin{aligned} (x,c)&=(406,0) && \text{initialise}\\ &\longrightarrow(40,1) && \text{remove }6\\ &\longrightarrow(4,2) && \text{remove }0\\ &\longrightarrow(0,3) && \text{remove }4 \end{aligned}

Why this step? Initialising c=0c=0 correctly counts the removals for non-zero inputs, but zero itself has no removals. Its one-digit representation needs the separate branch.

Answer. The instructions above output 33 for 406406, and 11 for 00.

Check. A one-digit non-zero input reaches x=0x=0 after one removal, so its output is 11, as required.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account