Computer programming - Homework + Lab 2

Homework

1. Write a function that given a natural number computes the value resulting from the digits of its decimal representation when interpreted as a hexadecimal number. Example: f(312) = 3 * 256 + 1 * 16 + 2 = 786
Hint: use the same recursive decomposition, but when reconstructing the number, use the new base (16).

2. Write a function that computes the value of a given series, until the current term becomes smaller than a given value (e.g. 1e-6). Write solutions for the Taylor series for ex and sin (for a given value of x).
Hint: pass the sum computed so far as one of the arguments. To avoid wasteful computation, you may also pass the current term as one of the arguments, and compute the next term starting from the current term.

3. Write a function that takes a natural number as argument and returns the value of the number read backwards (with the decimal digits in opposite order): f(3120) = 213. (This is a classic, it works the same way as list reversal).

4. Write a function that computes with a given precision (say, 1e-6) the limit of the sequence xn+1 = f(xn) (assuming it exists), with x0 and f given.
Your program should define a suitable f as a separate C function, for example f(x) = √x+2, with x0 some nonnegative number of your choice ≥ -2.
(Later we will learn how a pointer to f could be passed to the limit function.)
A value for which f(x) = x (which you are asked to compute) is called a fixpoint of the function (applying f results in the same value).
Use this approach to compute values of infinite terms, such as 1/(a+1/(a+1/(... + 1/a))) or √a+√a+ ...√a (for given values of a).
Hint: find the function f that transforms the term with n occurrences of a into the term with n+1 occurrences.

5*. Write a recursive function that returns the number of ways in which a natural number can be written as a sum of ones, twos and threes, irrespective of order.
Example: 5 = 1 + 1 + 1 + 1 + 1 = 1 + 1 + 1 + 2 = 1 + 2 + 2 = 1 + 1 + 3 = 2 + 3 (5 combinations).
Hint: If we use a value of 3, we are left with writing n - 3 in all possible ways. If we do not use 3, we must write n using only ones and twos (we can write another function for this problem).
Does the function perform wasteful computation ? Generalize for three arbitrary values instead of 1, 2, and 3.

6. If p is a prime number, the nonzero remainders modulo p (1 to p-1) form a multiplicative group Zp*. In a group the order of an element a is the smallest positive number n such that an = 1 (in this case, an ≡ 1 mod p). Write a function that takes as parameters an unsigned number p (assumed to be prime, no check for now) and an unsigned number a and returns the order of a (or zero, if p divides a).

Marius Minea
Last modified: Tue Oct 6 9:45:00 EEST 2015