Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
October 1, 2010
1 Smart Exponentiation
The straightforward possibility to raise a number x to a nonnegative integer
power n consists in repeated multiplication:
xn = x
|
· · × x},
× ·{z
n times
which is obvious but very inefficient (avoid at all costs!). Secure web connec-
tions heavily rely on raising big numbers to big powers, and never use the
straightforward approach above (except, maybe M$-made).
There is a smarter approach. Imagine, you want to compute x1024 .
Straightforwardly, you’ll need to make 1023 multiplications, which will keep
you busy for a while (try 31024 by pencil and paper during the weekend).
In contrast, I can do the same with just 10 multiplications, by repeated
squaring:
1. m2 = x × x = x2 ,
2. m4 = m2 × m2 = m22 ,
1
3. m8 = m4 × m4 = m24 ,
4. m16 = m8 × m8 = m28 ,
(Clearly, mi = xi .)
Similarly, you can do the same trick for n not being the power of 2
(1024=210 ). For example, x15 is computed with 6 multiplications as follows:
6. to compute x2 I need x × x.
(Hint: isn’t it dependent on ...? How the choice between squaring 2 and
multiplication ×x for computing xi depends on i?)
Devise an algorithm and implement. Count (and explain) the number of
multiplications and squarings performed for test inputs from the keyboard.
2
A
C D
B
G H I J
E F
2 General Trees
Binary trees (we extensively studied) are sufficient to represent any tree
structure (trees of arbitrary branching degree, not just 2). An example of a
tree with unary, binary, and ternary nodes is given in Figure 1.
To represent a general tree using binary nodes:
1. use the left reference on each node to indicate the first child of the
current node,
2. use the right reference to indicate a sibling, i.e., a child with the same
parent as the current node.
1. appropriate constructors,
2. method numberOfChildren of a node,
3. method child(i) returning the reference to the i-th child of a node (if
exists),
4. method addChild to a node,
(this will allow you to construct the tree from Figure 1; do it)
3
A
B C D
H I J
E F G
6. method mirror to reconstruct a tree into one that you will see in the
mirror you put on the left or right of Figure 1 (you do not need to
invert letters, which would be easy for A, H, I, but more difficult for
other letters).
Good Luck!