Download Problems set 1

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Vincent's theorem wikipedia , lookup

Series (mathematics) wikipedia , lookup

Sequence wikipedia , lookup

Algorithm wikipedia , lookup

Factorization of polynomials over finite fields wikipedia , lookup

Location arithmetic wikipedia , lookup

Collatz conjecture wikipedia , lookup

Positional notation wikipedia , lookup

Addition wikipedia , lookup

Arithmetic wikipedia , lookup

Elementary mathematics wikipedia , lookup

Elementary arithmetic wikipedia , lookup

Proofs of Fermat's little theorem wikipedia , lookup

Approximations of π wikipedia , lookup

Transcript
ALGORITHMS. Seminar 1: Problem solving techniques. Algorithms and properties. Describing the algorithms in pseudocode.
1. (S) Let us consider the following method to multiply two integers x and y: ”We write x and
y on the top of two columns. We successively divide x by 2 and write the quotients below
x (the remainder of the division is ignored). For each division of x by 2 we multiply y by 2
and write the result below y. The procedure continues by constructing in this manner two
columns of numbers. The computation stops when on the first column we obtain the value
1. Then we add all the values in the second column which correspond to odd values in the
first column”. This method is called multiplication ”à la russe” because the Russian peasants
used to use it. Let us consider the following example:
Example. Let x = 13 and y = 25. The sequence of values obtained by applying the above
procedure is:
x
13
6
3
1
y
25
50
100
200
325
remainder
1
0
1
1
multiplication factor for y
20
21
22
23
(a) Is this method an algorithm ? (b) Does it give the correct product of these numbers ? (c)
How many multiplications are executed ? Does this number depend on the order of factors ?
Hint. Due to the successive divisions by 2 the values on the first column are decreasing until
a quotient equal to 1 is obtained. Thus the process is finite. The correctness of the result
derives from the fact that the method realizes the binary conversion of x and the product is
obtained by successively multiplying the second number with powers if 2 and by adding only
those products which correspond to binary digits equal to one.
c) The number of multiplications by 2 is equal to the number of the binary representation of
x minus 1, i.e. blog2 xc. If there is a significant difference between x and y it is more efficient
if the first operand is the smaller one.
2. (S) Propose an algorithm to compute the integer part of a real number by using only repeated
additions or subtractions.
Hint. The computation depends on the sign of the number. When it is positive then one
have to successively subtract 1 from the number until one obtains a value less than 1. The
number of executed subtractions represent the integer part we are looking for. For negative
numbers one successively add 1 to the number until one obtains a value greater than 0.
Example.
x
3.25
2.25
1.25
0.25
x>0
counter
0
1
2
3
x<0
x
counter
−3.25
0
−2.25
−1
−1.25
−2
−0.25
−3
0.75
−4
1
3. (S) Let us consider a set of n identical coins except one about which we know that it has a
smaller weight. We want to identify the coin with smaller weight by using a simple balance.
Hint. A first variant would be to randomly select two coins and compare their weights by
using the balance. If one of them has a smaller weight then this is the coin we are looking for.
If both have the same weight we keep one on the balance and successively put the remaining
coins on the other part of the balance. The number of comparisons made in this way is n − 1.
Another variant would be to divide the set in two subsets of equal size (each set will have
n/2 elements, if n is even, respectively (n − 1)/2 if n is odd) which are placed on the balance
plates. If the subsets have the same weight (this can happen only if n is odd) then the ignored
coin is that we are looking for. Otherwise we apply the same strategy to the subset of smaller
weight. The procedure continues until we arrive to a set containing two or three coins. At
this moment one comparison is enough to identify the fake coin. The number of comparisons
is of the order of blog2 nc
4. (S) The chef of a restaurant is sloppy, and when he prepares a stack of pancakes they come
out all of different sizes. Therefore, when the waiter deliver them to a customer, on the way
to the table he rearrange them (so that the smallest winds up on top, and so on, down to
the largest at the bottom) by using only a spatula. How manage the waiter to rearrange the
pancakes ? Describe the problem in a more abstract manner.
Hint. He grabs several pancakes from the top and flips them over such that the bigger arrives
at the bottom of the stack. He repeats this action as many times as necessary.
Example. The sequence (5, 3, 4, 1, 6, 2) can be decreasingly sorted by applying the following
sequence of operations (where the subarray which is flipped is marked):
534162
534126
621435
653412
653214
654123
654321
The method consists in finding the maximum in the array and in inverting the order of
elements which starts with this value. In this way the maximum arrives on the last position.
By inverting the order of elements in the entire sequence the maximum arrives on the first
position. The same strategy is applied for the subsequence starting with the second element,
then with the third element and so on.
5. (S) Let us consider the following two problems:
(a) A person is at shopping and she has two bags. Her problem is to distribute as evenly as
possible the products which she bought in the two bags.
(b) Let us consider two storage devices (for instance hard disks) and a set of files whose total
size is less than the capacity of the two storage devices. The problem is to distribute as evenly
as possible the set of files on the two storage devices.
Does exist a relationship between the two problems ? Propose a solving method.
Hint. Both problems can be described in an abstract manner as follows: one consider a set of
positive numbers, A = {a1 , a2 , . . . , an } and one have to find two subsets, B and C such that
2
B ∪ C = A, B ∩ C = ∅ and |
X
a−
a∈B
X
a| is minimal. The simplest, but the less efficient
a∈C
method, method to solve this abstract problem is that of brute force. This means generating
all subsets B of A and their complement C and one choose from them that which minimizes
the difference. The number of distinct partitions (B, C) of A is around 2n−1 − 1. When n is
large these numbers becomes very large (for instance when n = 100 they are of the order of
1029 . A more efficient method should be found ...
6. (S+L) Let n be a non-zero natural number. Describe in pseudocode algorithms for:
(a) Computing the sum of all digits of number n. For instance for n = 26326 one obtains
the value 19.
(b) Finding the value obtained by reversing the order of digits in n. For instance, for the
value 26326 one obtains 62362.
(c) Constructing the set of all digits of n. For instance, for the value 26326 one obtain the
set {2, 3, 6}.
(d) Finding all binary digits of n.
(e) Finding all proper divisors of n (divisors which are not 1 or n).
(f) Deciding if n is prime or not (the algorithm should return true if the number is prime
and false otherwise.
(g) Decomposing n in prime factors. For instance for 490 = 21 · 51 · 72 one obtains the
following set of prime factors: {2, 5, 7} and their corresponding exponents: {1, 1, 2}.
Solution.
(a) The digits of the number are obtained by successive divisions by 10. At each step the
remainder will indicate the last digit of the current value while the quotient will be the next
value which will be divided by 10. When a digit is obtained it is added to a variable containing
the sum.
sum digits(integer n)
integer S
S←0
while n > 0 do
S ← S + nMOD10
n ← nDIV10
endwhile
return S
(b) If n = ck 10k +. . . c1 10+c0 the number we are searching for is m = c0 10k +. . . ck−1 10+ck =
(. . . (c0 10 + c1 )10 + c2 + . . . ck−1 )10 + ck . The digits of n are extracted starting with the last
one by successive divisions by 10. In order to construct m it is enough if we initialize m with
0 and for each digit extracted from n one multiplies m by 10 and add the obtained digit. The
algorithm can be described as:
3
reversed number(integer n)
integerm
m←0
while n > 0 do
m ← m ∗ 10 + nMOD10
n ← nDIV10
endwhile
return m
(c) The digits are obtained by successive divisions by 10. The set of digits can be represented
either by using an array with 10 elements containing presence flags (the element on position
i, i = 0, 9 is 1 if the digit i is in the number and 0 otherwise) or by storing in an array all
distinct digits from the number. In the first case the algorithm can be described as:
digits set(integer n)
integer c[0..9], i
for i ← 0, 9 do
c[i] ← 0
endfor
while n > 0 do
c[nMOD10] ← 1
n ← nDIV10
endwhile
return c[0..9]
In the second case, for each extracted digit we have to check if it is not already in the array
with digits
digits set(integer n)
integer c[1..i], i, j
i←0
while n > 0 do
r ← nMOD10
j←1
prezent ← false
while j <= i AND prezent =false do
if c[j] = r then prezent ← true
else j ← j + 1
endwhile
if prezent =false then
i←i+1
c[i] ← r
endif
n ← nDIV10
endwhile
return c[1..i]
(d) The binary digits of n are obtained by successive divisions to 2 until is obtained quotient
is 0. The remainder of the first division is the least significant digit, while the remainder
4
obtained by the last division is the most significant digit. If 2k−1 ≤ n < 2k then the binary
value can be represented on k positions and the algorithm can be defined as:
binary digits(integer n)
integerb[0..k − 1],i
i←0
while n > 0 do
b[i] ← nMOD2
i←i+1
n ← nDIV2
endwhile
return b[0..i − 1]
In order to have the array with the binary digits in the natural order (starting with the
most significant digit) it is enough if we reverse the order of elements in the array. The
corresponding algorithm can be described as follows:
for j ← 0, b(i − 1)/2c do
b[j] ↔ b[i − 1 − j]
endfor
In the above algorithm the swapping operator, ↔, corresponds to three assignments which
need the use of an auxiliary variable (aux) to temporarily store the value of one of the
variables:
a↔b
aux ← a
a←b
b ← aux
(e) To find the proper divisors of n (divisors which are neither 1 nor n) it is enough to analyze
the values between 2 and bn/2c. The algorithm which prints all proper divisors are:
divisors(integer n)
integer i
for i ← 2, bn/2c do
if nMODi = 0 then write(i) endif
endfor
(f) We start from the hypothesis that the number is prime and therefore we initialize the
variable which will contain the result with true. Then we check if n has proper divisors and
if we find at least one divisor we can decide that the number is not prime.
5
prime(integer n)
integer i
boolean p
p ← true
i←2
√
while i <= b nc AND p =true do
if nMODi = 0 thenp ← F alse
else i ← i + 1
endif
endwhile
(g) The decomposition of a number in prime factors consists of two sequences of values: the
sequence of prime factors and their corresponding exponents. Therefore we shall use two
arrays, f and p, to represent the decomposition. The algorithm is similar to that finding the
divisors but when a divisor is found the number is divided by it as many times is possible.
In this way all detected factors are prime and the number of possible divisions by one factor
denotes the corresponding exponent.
prime factors(integer n)
integer f [1..k], p[1..k],i,d
i←0
d←2
repeat
if nMODd = 0 then
i←i+1
f [i] ← d
p[i] ← 1
n ← nDIVd
while nMODd = 0 do
p[i] ← p[i] + 1
n ← nDIVd
endwhile
endif
d←d+1
until n < d
return f [1..i], p[1..i]
7. (S+L) Let n be a natural number, x ∈ (0, 1) and > 0 positive real value. Describe in
pseudocode algorithms for:
(a) Computing the sum
Pn
(b) Estimating the sum
P∞
i 2i
i=1 (−1) x /(2i)!.
i 2i
i=1 (−1) x /(2i)! with
precision .
Solution.
(a) The sum can be rewritten as S = T (1) + . . . + T (n) cu T (i) = (−1)i x2i /(2i)!. In order
to reduce the number of computations we shall use the following relation between successive
terms: T (i) = −T (i − 1) ∗ x2 /((2i − 1)2i) with T (1) = −x2 /2. The algorithm can be described
as:
6
sum(integer n, real x)
integer i
real S, T
T ← −x ∗ x/2
S←T
for i ← 2, n do
T ← −T ∗ x ∗ x/((2 ∗ i − 1) ∗ 2 ∗ i)
S ←S+T
endfor
return S
(b) An infinite sum (series) can be estimated by adding finite number of terms until the last
term become small enough (this can be applied only when the series is convergent). We
shall consider that the estimation has precision if the last term added to the sum satisfies
|T (i)| < .
estimated sum(integer n, real x,real eps )
integer i
real S, T
T ← −x ∗ x/2
S←T
i←1
repeat
i←i+1
T ← −T ∗ x ∗ x/((2 ∗ i − 1) ∗ 2 ∗ i)
S ←S+T
until |T | < eps
return S
8. (S+L) Print the first N elements and estimate (with precision ) the limits of the following
sequences (excepting from the sequence defined in (d) which is not necessarily convergent):
(a) xn = (1 + 1/n)n ;
(b) x1 = a > 0, xn = (xn−1 + a/xn−1 )/2;
(c) xn = fn+1 /fn , f1 = f2 = 1, fn = fn−1 + fn−2 ;
(d) x1 = s, xn = (axn−1 + b)MODc, a, b, c ∈ N ∗ .
Solution.
(a) Printing the first N elements of the sequence xn can be described as:
sequence(integer N )
integer n
for n ← 1, N do
write (1 + 1/n)n
endfor
In the case of a convergent sequence, the limit can be approximated by the element xL which
satisfies |xL − xL−1 | < . In this case is useful to store in separate variables both the current
value (xc) and the previous value of the sequence (xp).
7
limit sequence(real eps)
integer n
real xc, xp
n←1
xc ← 2
repeat
xp ← xc
n←n+1
xc ← (n + 1/n)n
until |xc − xp| ≤ eps
return xc
(b) To find the elements of a sequence given through a recurrence relation of order r, xn =
f (xn−1 , . . . , xn−r ) it is enough if we use r + 1 variables: r of them the previous values in
the sequence (p1 , . . . pr ) and one will contain the current value (p0 ). The algorithm can be
described as:
recurrent sequence(integer N , real x[1..r])
integer i
real p[0..r]
p[1..r] ← x[1..r]
for i ← r + 1, N do
for k ← r, 1, −1 do
p[k] ← p[k − 1]
endfor
p[0] ← f (p[1], . . . , p[r])
writep[0]
endfor
When r = 1 the algorithm becomes simpler:
recurrent sequence(integer N , real a)
integern
real x
x←a
for n ← 2, N do
x ← (x + a/x)/2
write x
endfor
The estimation of the limit of this sequence (which converges
8
√
a) can be computed as follows:
limit(integer N , real a)
integer n
real xp,xc
xc ← a
repeat
xp ← xc
xc ← (xp + 1/xp)/2
until |xp − xc| < eps
return xc
(c) The sequence fn is given through a recurrence relation of order 2 and it is known as
Fibonacci’s sequence. To generate the elements of xn one has to generate first the elements
of Fibonacci’s sequence (by using, for instance, three variables: f0 - for the current element,
f1 and f2 for the previous elements).
sequence(integer N )
integer n, f 0,f 1
real x
f 0 ← 1 // the second element
f 1 ← 1 // the first element
for 1 ← 3, N do
write f 0/f 1
f2 ← f1
f1 ← f0
f0 ← f1 + f2
endfor
It can be proved that xn converges to θ = (1 +
can be described as follows:
√
5)/2. The algorithm to estimate the limit
limit sequence(real eps)
integer f 0, f 1
real xc, xp
f0 ← 1
f1 ← 1
xc ← f 0/f 1
repeat
xp ← xc
f2 ← f1
f1 ← f0
f0 ← f1 + f2
xc ← f 0/f 1
until |xc − xp| ≤ eps return xc
(d) The recurrence relations of this type are used to generate pseudo-random values and are
used to implement random algorithms. The generated values are between 0 and c − 1.
9
random sequence(integer N , s, a, b, c)
integer x
x←s
for n ← 2, N do
x ← (a ∗ x + b)MODc
write x
endfor
Homework
1. Describe in pseudocode the algorithm corresponding to multiplication ”à la russe”.
2. Describe in pseudocode the algorithm corresponding to the sorting method based on flipping
a final subsequence in a sequence (the pancake problem).
3. Find an method which for two sequences having the same number of elements decides if one
can be obtained from the other one by reversing the order of elements of a suffix (e.g. for
two sequences x = (x1 , x2 , . . . , xn ) and y = (y1 , y2 , . . . , yn ) there exists 1 ≤ k ≤ n such that
xk+i−1 = yn−i+1 for i = 1, n − k).
4. Write an algorithm to count how many digits are equal to 1 in the binary representation of
a natural value n.
5. Write an algorithm to find the most frequent in a natural n. If there are several such digits
all of them will be printed.
Pn
6. Write an algorithm to compute
the corresponding infinite sum.
i+1 x2(i+1) /(2(i + 1))!
i=1 (−1)
and to estimate with precision
7. Write an algorithm to print the first N elements of the Fibonacci’s sequence by using only
two auxiliary variables.
Supplementary problems.
1. Compute the value in basis 10 of a natural number starting from the sequence of the binary
digits. The algorithm should contain only basic operations: addition, subtraction, multiplication, division (computing the power of a number is not considered a basic operation). Try
to use as few as possible operations.
2. Let us consider a sequence of non-zero values (the sequence contains both positive and negative
values). Transform the sequence such that all negative values are before the positive ones.
Try to use as few as possible operations.
3. Let us consider a sequence of n − 1 distinct values belonging to the set {1, 2, . . . , n}. Find,
by using as few as possible operations the values which is missing from the sequence.
10