Computer science is often treated as an engineering discipline, and a central goal of engineering is solving problems. This chapter introduces algorithms, which are systematic methods for solving problems. It also introduces pseudocode, a useful tool for describing and analysing algorithms, together with number representations used in computer science.
Numbers
Every reader could be quite surprised when seeing the title for this section. Yes, numbers, we have known what is number since the very beginning when we get to learn math as toddlers. In this section, we will explain the system of number, not only will we figure out how numbers and their operations are defined, but how they are categorized.
Typology of Numbers
This part recalls the type of numbers we’ve learned since primary school and their set notations.
-
Natural Numbers
-
Definition: Natural numbers are the set of positive integers used for counting and ordering, which do not include zero or negative numbers.
-
Set Notation:
-
-
Integers
-
Definition: Integers are all the whole numbers including positive natural numbers, their negatives, and zero.
-
Set Notation:
-
-
Rational Numbers
-
Definition: Rational numbers are numbers that can be expressed as the quotient of two integers, a fraction , where and are integers and . The set includes all integers and fractions.
-
Set Notation:
-
For numbers that are written in finite decimal places, if there is a looping part in the decimal places, it is still recognized as rational numbers. For instance, could be represented as . Usually, we use upperline to mark the repeating part, in this case it is. But for those who have infinitely non-repeating decimal places, such as , we categorize it as irrational number, as they cannot be written in the form.
-
Irrational Numbers
-
Definition: Irrational numbers are real numbers that cannot be expressed as a ratio of two integers. The decimal expansion of irrational numbers is non-terminating and non-repeating. Examples include and .
-
Set Notation: (Note: is used here for illustrative purposes and is not a standard symbol.)
-
-
Real Numbers
-
Definition: The real numbers include both rational and irrational numbers, encompassing all points on an infinitely extended number line. The set of real numbers is continuous and is composed of all limits of sequences of rational numbers.
-
Set Notation:
-
-
Prime Numbers
-
Definition: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In other words, is prime if and if is divisible only by 1 and .
-
Set Notation:
-
Examples: The first few prime numbers are:
The following Venn diagram shows the relationship between different number sets.
-
Figure pending: Venn Diagram of Number Sets
Complex number is currently not a something necessary, as our discussion so far only falls in the real number set.
The Real Number System
Considering the real numbers are the only system involved so far this book, here, we provide a new mathematical perspective that is different what we were taught, to understand the real number system. We will introduce three axioms that real number holds.
A set with operations and and distinguished elements 0 and 1 with is a field if the following properties hold for all :
-
Closure
-
Associativity
-
Commutativity
-
Identity
-
given , there is a such that Inverse
-
Closure
-
Associativity
-
Commutativity
-
Identity
-
for , there is a such that Inverse
-
Distributive Law
The operations and are called addition and multiplication. The elements 0 and 1 are the additive identity element and the multiplicative identity element, respectively.
It follows from these axioms that the additive inverse and multiplicative inverse (of a nonzero ) are unique. The additive inverse of is the negative of , written as . To define subtraction of from , we let . The multiplicative inverse of is the reciprocal of , written as . The element 0 has no reciprocal. To define division of by when , we let . We write as and as . We use parentheses where helpful to clarify the order of operations.
A positive set in a field is a set such that for ,
-
implies Closure under Addition
-
implies Closure under Multiplication
-
implies exactly one of , , Trichotomy
An ordered field is a field with a positive set . In an ordered field, we define to mean . The relations and have analogous definitions in terms of .
Note that . Another phrasing of trichotomy is that each ordered pair satisfies exactly one of , , . If , then is an upper bound for if for all .
An ordered field is complete if every nonempty subset of that has an upper bound in has a least upper bound in .
This theorem ensures the square roots of positive real numbers.
Axiom axi
and axi imply many familiar property of arithmetic:Each of , , and is closed under addition and multiplication, and are closed under subtraction, and the set of nonzero numbers in is closed under division.
The next four propositions state properties of an ordered field . All statements apply for each choice of .
Elementary consequences of the field axioms.
Floor, Ceiling, and Remainder
This Section discusses more form numbers that may not be as familiar as real numbers. We first introduce Integer Function:
If is any real number, we write \lfloor x \rfloor = \text{the greatest integer less than or equal to \( x ) (the floor of \( x ))} \lceil x \rceil = \text{the least integer greater than or equal to \( x ) (the ceiling of \( x ))}
Note that the could be not just a variable, but a mathematical expression.
Properties of Integer Function
We will look into the properties of integer function with its graph.
Figure pending: Visualization of ⌈x⌉ and ⌊x⌋
Keep in mind the following important properties of integer function, which is often used in algorithm analysis or other mathematical proof.
-
-
-
-
;
-
The proofs to these conclusions are quite basic, and is therefore not provided here.
Remainder and Integer Function
We introduce a new operation that we have learned before in this section with its notation.
The modulo operation, denoted as , finds the remainder when one integer is divided by another integer . If divided by gives a quotient with remainder , then , and would be the result of .
Moving back to the integer function, we have:
Below is the proof to the first conclusion, where the properties of integer function are applied.
By the Division Algorithm, for any integer and any positive integer , there exist unique integers and such that and , where is the quotient and is the remainder. The floor function yields the largest integer less than or equal to , which by definition is the quotient . Thus, we have: and therefore: Subtracting this from gives: The uniqueness of the quotient and remainder in the Division Algorithm ensures that this value of is the remainder from the modulus operation. Therefore, we have: which is the remainder when is divided by , completing the proof.
Also, from definition, by dividing on both sides of the equation: Among which, .
By the definition of the modulo operation, can be written as . Since is the greatest integer less than or equal to , we have: Furthermore, because is less than , it follows that: Hence, .
And we have:
By above-mentioned conclusions:
-
If .
-
If .
-
.
We call the remainder when is divided by . We call the quotient. We have if and only if is a multiple of , that is, if and only if is divisible by . The notation , read ” divides ”, means that is a positive integer and .
exercises
Let be a field consisting of exactly three elements . Prove that and that . Obtain the addition and multiplication tables for .
Hint: Think on the property of filed: inverse of addition and multiplication.
Since is a field, it has the properties of both a group under addition and a group under multiplication (excluding for the latter).
Part 1: Proof that
-
In a group, every element has an additive inverse. In , the additive inverse of is itself, since .
-
The additive inverse of cannot be itself because would imply , which is a contradiction. Therefore, ‘s additive inverse must be some other element of , which can only be . Hence, .
-
The element must also have an additive inverse in , which cannot be (as ‘s inverse is ) and cannot be (as ‘s inverse is ). The only option left is itself. Thus, .
-
Given and , by the cancellation law, it must be that . However, this contradicts the assumption that is distinct from . Therefore, our assumption that is incorrect.
-
The only remaining possibility is .
Part 2: Proof that
-
Similarly, in a multiplicative group (excluding ), every non-zero element has a multiplicative inverse. For , the multiplicative inverse is itself since .
-
The element must have a multiplicative inverse. It cannot be since is not invertible, and it cannot be since is already serving as its own inverse.
-
The only remaining option for the multiplicative inverse of is itself. Hence, .
Now we construct the addition and multiplication tables for :
Addition Table:
Multiplication Table:
Is there a field with exactly four elements? Is there a field with exactly six elements?
Let be an integer, and let be a real number. Prove that:
-
if and only if ;
-
if and only if ;
-
if and only if ;
-
if and only if ;
-
if and only if ;
-
if and only if .
The defining inequality is
Because is an integer, each statement follows by comparing with the adjacent integers and . In particular, exactly when , and exactly when .
Using the previous exercise, prove that .
Let . By the definition of the ceiling function, Multiplying by reverses the inequalities: Thus is the greatest integer less than or equal to , so .
Prove that
for every .
We will prove the statement by cases.
When is even, let . .
When is odd, let . , and .
For the second identity, if then , while if then .
Algorithm and Algorithm Analysis
This Section discusses what is algorithm, and more importantly, how algorithms are assessed.
Algorithm
What is an Algorithm?
An algorithm is a well-defined, step-by-step procedure or sequence of instructions designed to solve a specific class of problems:
-
Each step in an algorithm must be clear and unambiguous.
-
Algorithms must be solvable, meaning they should be able to produce a correct solution for any valid input within a finite amount of time.
-
An algorithm must terminate, i.e., it should have a defined end, at which point the goal has been achieved and the final output is produced.
Here is an example of multiplication algorithm for better understanding of the concept.
To find the product of integers and , both larger than one:
-
Start two columns on a page, one labeled “A” and the other “B”; and put the value of under A and the value of under B.
-
Repeat
-
calculate a new A-value by multiplying the old A-value by 2; and
-
calculate a new B-value by dividing the old B-value by 2 and reducing the result by a half if necessary to obtain an integer;
Until the B-value equals one.
-
Go down the columns crossing out the A-value whenever the B-value is even.
-
Add up the remaining A-values and “return” the sum.
To show how it works, assume and .
A B
73 41 146 20 (20 is reduced to 20) 292 10 584 5 1168 2 (2 is reduced to 2) 2336 1
: Execution of RPM
Sum of the remaining A-values: .
Let’s review this algorithm referring to definition def
.-
Clarity and Accuracy: All the instructions are clear and manipulable, nothing is ambiguous.
-
Solvability: It is no doubt that for any two real numbers, we can find their product.
-
Termination: For which ever numbers, we can always solve the problem in limited steps, as the terminate condition is when , while B is divided by 2 (integer division) repetitively.
Hence, the RPM is a good example of algorithm, and with this, we could tell whether something else is an algorithm or not.
Pseudocode
Pseudocode is a simplified, half-code, half-natural language script used by software developers and algorithm designers to outline the structure of a program or algorithm. It’s not executable code, but rather a high-level representation of the algorithm’s logic. The purpose of pseudo-code is to express the design of an algorithm in a form that can be easily translated into actual programming languages. It is written in a way that is understandable to people who do not necessarily know the syntax of programming languages. Pseudo-code allows the designer to focus on the core logic of the algorithm without getting bogged down with the syntactic details of a particular programming language. It often uses control structures like if-then-else, while, for, and others that are common to many high-level languages. Understanding pseudocode is quite easy as it quite close to natural languages.
Here’s the RPM transcribed in pseudocode:
$product \gets 0$ $product \gets product + A$ $A \gets A \times 2$ $B \gets B \div 2$ **return** $product$To explicit:
-
procedure RPM(A, B): Defines a procedure or function named ‘RPM’ taking two parameters ‘A’ and ‘B’.
-
product 0: The assignment operator '' is used to assign the value on the right (0 here) to the variable on the left (‘product’).
-
while B 0 do: Begins a ‘while’ loop that continues as long as the condition ‘B 0’ is true. The ‘do’ indicates that the following block of code will execute if the condition is met.
-
if B is odd then: A conditional statement that checks if ‘B’ is odd. If it is, the subsequent statement is executed.
-
product product + A: An assignment operation that adds ‘A’ to ‘product’ and assigns the sum back to ‘product’.
-
end if: Marks the end of the ‘if’ statement.
-
A A 2: Multiplies the value of ‘A’ by 2 and then assigns the result back to ‘A’.
-
B B 2: Divides the value of ‘B’ by 2 (integer division) and assigns the result back to ‘B’.
-
end while: Marks the end of the ‘while’ loop.
-
return product: The ‘return’ statement indicates the output or result of the procedure, which here is the value of the variable ‘product’.
-
end procedure: Marks the end of the ‘RPM’ procedure.
All later algorithms in this book will be presented using pseudocode.
Algorithm Analysis
Now let’s take a look at this algorithm from another aspects. Is this a good or a bad algorithm. People assess algorithms by examine its complexity, which could be either space complexity or time complexity. The former refers to the the relationship between the input and the space needed to execute the algorithm, the latter, similarly, refers to the time needed. Many tools are available to quantify complexity, for both space and time complexity, the big O notation is the most common measurement.
Big O notation is used to classify algorithms according to how their running time or space requirements grow as the input size grows. The notation describes an upper limit on the time an algorithm could possibly take to complete, given the size of the input. For a function , where n is the scale of input for the algorithm, the Big O notation is formally defined as follows with as a positive constant:
The following table provides common time complexities using Big O notation:
Description
1 Constant Logarithmic n Linear Linearithmic Quadratic Cubic Exponential Factorial
: Common time complexities in Big O notation
We can visualize it using function graph
Figure pending: Time Complexity Visualization
So which space and time complexity does this algorithm fall in?
Time Complexity
To analyze the time complexity, we usually focus on the termination condition or the number of iteration for the algorithm. For the real number in RPM, each time it is divided by 2 until . Therefore, the total number of iteration will be , which is categorized in .
Actually, the time complexity of an algorithm could be shown by strict proof using MI. Here is the proof on the time complexity of RPM.
Proof: We will use mathematical induction to prove that the number of steps in the algorithm is proportional to .
Base Case:\ When , the algorithm requires only one step. This is consistent with , which satisfies our complexity class .
Inductive Hypothesis:\ Assume that for a positive integer , when , the algorithm operates within steps.
Inductive Step:\ Consider . In the first step of the algorithm, is halved to , and is doubled. From this point, based on our inductive hypothesis, reaching requires steps.
Hence, for , the total number of steps is . Using the properties of logarithms, we have:
Therefore, for any , the total number of steps is also , proving that for any positive integer , the time complexity of the Russian Peasant Multiplication is .
Space Complexity
The space complexity of the Russian Peasant Multiplication algorithm is determined by the amount of memory required to store the operands and the intermediate results. Initially, only two numbers need to be stored: the multiplicands. As the algorithm proceeds, we need additional space to keep track of the current product. Since the algorithm does not use any complex data structures and only requires a fixed number of variables, the space complexity is , indicating constant space usage. It does not depend on the size of the input operands, as the memory required does not increase with larger numbers.
Exercises
A non-recursive Square and Multiply Algorithm to calculate .
Precondition: is a positive integer and is of any type that can be multiplied.
Postcondition: the value returned is equal .
-
Show that the algorithm terminates. Let denote the value of after the th iteration of the while-loop, and let . Prove by Mathematical Induction on that For any nonnegative integer , after iterations of the while-loop:
-
Proof of correctness. Use Mathematical Induction on to prove For any nonnegative integer , after iterations of the while-loop:
$product \gets 1$ $square \gets b$ $a \gets n$ $product \gets product \times square$ $square \gets square \times square$ $a \gets \lfloor a / 2 \rfloor$ $product \times square$1. Base Case : For , , which is the initial value of . Since , it is the greatest integer less than or equal to , therefore . So, for , the predicate holds because:
Inductive Step: Assume holds for some nonnegative integer . That is: We need to show holds. During each iteration, is halved (integer division by 2), which gives us:
Since is an integer, will either be or , depending on whether is even or odd. Thus, we have:
Since , dividing by 2 gives , and therefore:
Similarly, implies , so we have: This completes the inductive step and thus, by induction, holds for all nonnegative integers .
2. We need to prove that after iterations of the while-loop, the invariant holds:
Base Case : Initially, , , and . So, is trivially true.
Inductive Step: Assume the invariant holds after iterations, i.e., Now, consider the th iteration. There are two cases:
Case 1 ( is odd): The product is updated by multiplying it with , and we have: Since is odd, we can write for some integer , and after the iteration, becomes . The invariant becomes:
Case 2 ( is even): The product remains the same, and can be written as , so the invariant remains: since and .
In both cases, after the iteration, is squared, so we get: and therefore, the invariant still holds as:
Thus, by mathematical induction, the invariant holds true for every iteration of the loop, proving the correctness of the algorithm.
Comments