## CS13002 Programming and Data Structures | ## Spring semester |

## Exercise set I

Note:Students are encouraged to solve as many problems from this set as possible. Some of these will be solved during the lectures, if time permits. We have made attempts to classify the problems based on the difficulty level of solving them. An unmarked exercise is of low to moderate difficulty. Harder problems are marked by H, H^{2}and H^{3}meaning "just hard", "quite hard" and "very hard" respectively. Exercises marked by M have mathematical flavor (as opposed to computational). One requires elementary knowledge of number theory or algebra or geometry or combinatorics in order to solve these mathematical exercises.

- Assume that the CPU of a particular computer has three general-purpose registers A,B,C. Assume also that m,n,t are integer values stored in the machine's memory. Write assembly instructions for performing the following assignments. Use an assembly language similar to that discussed in the examples given in the notes. Assume that all operations are integer operations.

- m = m + n - 1;
- t = (m+5)*(n+5);
- n = (m+5)/(n+5)+(n+5)/(m+5);
- [M] Let n be a non-negative integer less than 2
^{t}. Let (a_{t-1}a_{t-2}...a_{1}a_{0})_{2}be the t-bit binary expansion of n obtained by the repeated divide-by-2 procedure described in the notes. Prove that:n = a_{t-1}2^{t-1}+ a_{t-2}2^{t-2}+ ... + a_{1}2^{1}+ a_{0}.- Write the 8-bit 2's complement representations of the following integers:

- 123
- -123
- -7
- 63
- Find the 32-bit floating point representation of the following real numbers (under the IEEE 754 format):

- 123
- -123
- 0.1
- 0.2
- 0.25
- -543.21
- [H
^{2}M] Let x be a proper fraction, i.e., a real number in the range 0<=x<1. Prove that x has a terminating binary expansion if and only if it is of the form a/2^{k}for some integers a,k with 0<=a<2^{k}.- Let x,y,z be unsigned integers. Find the values of x,y,z after the following statements are executed.
x = 5; z = 12; x *= x; x += z * z; y = x << 1; z = y % z;- Assume that m and n are (signed) integer variables and that x and y are floating point variables. Write logical conditions that evaluate to "true" if and only if:

- x+y is an integer.
- m lies strictly between x and y.
- m equals the integer part of x.
- x is positive with integer part at least 3 and with fractional part less than 0.3.
- m and n have the same parity (i.e., are both odd or both even).
- m is a perfect square.
- Write a program to solve the following problems:

- Show that -29 and 31 are roots of the polynomial
x. What is its third root?^{3}+ x^{2}- 905x - 2697- Show that -2931 is a root of the polynomial
x.^{3}+ 2871x^{2}- 174961x + 2634969- The three roots of the polynomial
xare integers. Find them.^{3}+ x^{2}- 74034x + 5294016- The three roots of the polynomial
xare again integers. Find them.^{3}+ x^{2}- 28033x - 1815937- Read five positive real numbers a, b, c, d and e from the user and compute their arithmetic mean, geometric mean, harmonic mean and standard deviation.
- Input four integers a, b, c and d with b and d positive.

- Output the rational numbers (not their float equivalents) (a/b)+(c/d), (a/b)-(c/d) and (a/b)*(c/d).
- Output the rational numbers (a/b)+(c/d), (a/b)-(c/d) and (a/b)*(c/d) in lowest terms, that is, in the form m/n with n>0 and gcd(m,n)=1.
- Input four integers a, b, c and d with a or b (or both) non-zero and with c or d (or both) non-zero.

- Output the complex numbers (a+ib)/(c+id) and (c+id)/(a+ib) in the form (r/s)+i(u/v) with r,s,u,v integers and s,v>0.
- Output the complex numbers (a+ib)/(c+id) and (c+id)/(a+ib) in the form (r/s)+i(u/v) with r/s and u/v in lowest terms, that is, with s,v>0 and with gcd(r,s)=gcd(u,v)=1.
- Let m and n be 32-bit unsigned integers. Use bit operations to assign to m the following functions of n:

- 1 if n is odd, 0 if n is even.
- 1 if n is divisible by 4, 0 otherwise.
- 2
^{n}(Assume that n<=31).- n rotated by k positions to the left for some integer k>=0.
- n rotated by k positions to the right for some integer k>=0.
- Write a program that does the following: Scan six real numbers a,b,c,d,e,f and compute the point of intersection of the straight lines:
ax + by = c dx + ey = fYour program should specifically handle the case that the two given lines are parallel.

- Write a program to determine the roots of a quadratic equation. Figure out a way to handle the case when the the roots are not real.
- Write a program that scans a string and checks if it represents a valid date in the format DD-MM-YYYY. (Example: 29-02-2005 is not a valid date, but 29-02-2004 is valid.)
- An ant is sitting at the left end of a rope of length 10 cm. At t=0 the ant starts moving along the rope to reach the other end of the rope. The ant has a speed of 1 cm per second. After every second the rope stretches instantaneously and uniformly (along its length) by 10 cm with the left end fixed at the point from where the ant started its journey. Suppose that the ant's legs provide it sufficient friction in order to withstand the stretching of the rope. Write a program to demonstrate that the ant will be able to reach the right end of the rope. Your program should also calculate how many seconds the ant would take to achieve this goal. You may assume that the length of the ant is negligible (i.e., zero).

Note:The ant would reach the right end of the rope, even if its initial length and stretching per second were 1 km (or even a billion kilometers) instead of 10 cm. But for these dimensions the ant would take such an unbelievably large time that your program will not give you the confirmation in your life-time. Moreover, you will require more precision than whatdoublecan provide. Try to solve this puzzle mathematically.- Randomly generate a sequence of integers between -5 and +99 and output the maximum and minimum values generated so far. Exit, if a negative integer is generated. You must not store the sequence generated (say using an array), but update the maximum and minimum values on the fly, as soon as a new entry is generated. A sample run is given below:
Iteration 1: new entry = 84, max = 84, min = 84 Iteration 2: new entry = 87, max = 87, min = 84 Iteration 3: new entry = 72, max = 87, min = 72 Iteration 4: new entry = 53, max = 87, min = 53 Iteration 5: new entry = 93, max = 93, min = 53 ...- It is known that the harmonic number H
_{n}converges tok + ln nas n tends to infinity. Herelnis the natural logarithm and k is a constant known asEuler's constant. In this exercise you are asked to compute an approximate value for Euler's constant. Generate the values ofHand_{n}ln nsuccessively forn=1,2,3,..., and compute the differencek. Stop when_{n}= H_{n}- ln nkis less than a specific error bound (like_{n}-k_{n-1}10).^{-8}

Note:It is not known whether Euler's constant is rational or not. It has, however, been shown that if Euler's constant is rational, its denominator must have more than 10,000 decimal digits.- Write a program that, given a positive integer n, determines the integer t with the property that
2. This integer t is called the^{t-1}<=n<2^{t}bit-lengthof n.- A
Pythagorean tripleis a triple (a,b,c) of positive integers with the property that a^{2}+b^{2}=c^{2}. Write a program that scans a positive integer value k and outputs all Pythagorean triples (a,b,c) with 0<a<=b<c<=k.- Consider the function
f(a,b) = (a^{2}+b^{2})/(ab-1)of two positive integers a,b with ab>1.

- Write a program that scans a positive integer k and prints the three values a,b,f(a,b) if and only if 0<a<=b<=k and f(a,b) is an integer.
- [H
^{3}M] Do you see a surprising fact about these f(a,b) values? Can you prove your hunch?- Given a number in decimal write a program to print the reverse of the number. For example, the reverse of 3481 is 1843.
- Write a program that does the following: Read a decimal integer and print the ternary (base 3) representation of the integer.
- Write a program that does the following: Read a string of 0's and 1's and print the decimal equivalent of the string treated as an integer in the binary representation.
- [H] Write a program that does the following: Read a string of 0's, 1's and 2's and print the decimal equivalent of the string treated as an integer in the ternary representation.
- Write a program that, given a positive number x (not necessarily integral) and an integer k, computes the kth root of x using the bisection method. Supply an accuracy for your answer.
- Generate a random sequence of birthdays and store the birthdays in an array. As soon as a match is found, report that. Also report how many birthdays were generated to get the match.

Note:It is surprising to see that you usually require a very small number of people (around 25) in order to have a match in their birthdays. However counter-intuitive it might sound, it is a mathematical truth, commonly known as thebirthday paradox. In short it says that if you draw (with replacement) about sqrt(n) samples from a pool of n objects, there is about 50/50 chance that you get a repetition. If you draw 2 sqrt(n) samples, you can be almost certain that there will be at least one repetition.- Write a program that, given an array
A[]of integers, finds out the largest and second largest elements of the array.- Write a program that, given an array
A[]of signed integers, finds out a subsequencei,i+1,...,jsuch that the sumA[i] + A[i+1] + ... + A[j]is maximum over all such subsequences. Note that the problem is trivial if all numbers are positive -- your algorithm should work when the numbers may have different signs.- [H
^{2}] Can you write a program that solves the problem of the last exercise using roughly n operations?- Read an English sentence from the terminal. Count and print the number of occurrences of the alphabetic letters (a through z) in it. Also print the total number of distinct alphabetic letters in the sentence. Make no distinction between upper and lower case letters, i.e., 'a' is treated the same as 'A', 'b' the same as 'B' and so on. Neglect non-alphabetic characters (digits, spaces, punctuation symbols etc.).
- Input two strings a and b from the user and check if b is a substring of a. If b is a substring of a, then your program should also print the leftmost position of the leftmost match of b in a.
- Write a program that scans a positive integer and checks if the integer is a perfect number (i.e., a number which is equal to the sum of all its proper integral divisors, e.g., 6 = 1+2+3).
- Write a program that reads a positive integer n and lists all primes between 1 and n. Use the
sieve of Eratosthenesdescribed below:Use an array of n cells indexed 1 through n. Since C starts indexing from 0, one may, for the ease of referencing, use an array of n+1 cells (rather than n). Initially all the array cells are unmarked. During the process one marks the cells with composite indices. An unmarked cell holds the value 0, a marked cell holds 1. Henceforth, let us abbreviate "marking the cell at index i" as "marking i".

Any positive integral multiple of a positive integer k, other than k itself, is called a

proper multipleof k. Starting with k=2, mark all proper multiples of 2 between 1 and n. Then look at the smallest integer >2 that has not been marked. This is k=3 and must be a prime. Mark all the proper multiples of 3 and then look at the next unmarked integer -- this is k=5. Then mark the proper multiples of 5 and so on. The process need continue as long as k<=sqrt(n), since every composite integer m, 1<m<=n, must have a prime divisor <=sqrt(n).After the loop described in the last paragraph terminates, report the indices of the unmarked cells in your array. These are precisely all the primes in the range

1,2,...,n.Now adjust the bound n in order to detect the millionth prime.

- [HH] Repeat the above problem where a cell is marked at most once. In the previous description, cell 6 will will get marked when we consider 2 as well as 3 etc.
- [HM] Write a program that, given two integers a,b with 0<a<b, finds integers n
_{1},n_{2},...,n_{k}with the properties that:n_{1}< n_{2}<...< n_{k}and a/b = 1/n_{1}+ 1/n_{2}+ ... + 1/n_{k}.(Hint: You may use the following idea. If a/b is already of the form 1/n, we are done. Otherwise, find the integer n such that 1/n<a/b<1/(n-1). Print n, replace a/b by (a/b)-(1/n) and repeat. Prove that this gives a strictly increasing sequence of printed values (n) and that the process terminates after finitely many steps.)

- Write a program that, given a set of n points in the plane (specified by their x and y coordinates), determines the smallest circle that encloses all these points. (Hint: The smallest circle must either pass through three given points or have two given points at the opposite ends of a diameter.)
- In this exercise you are asked to compute approximate values of pi.

- Write the infinite series for 1/(1+x
^{2}).- Integrate (between 0 and x) both 1/(1+x
^{2}) and the infinite series for it, put the value x = 1/sqrt(3) and write pi as an infinite series.- Truncate the series after n terms and evaluate the truncated series to get an approximate value of pi. Use the values n=10
^{i}for i=1,2,...,6.

- Write the infinite series for 1/sqrt(1-x
^{2}).- Integrate (between 0 and x) both 1/sqrt(1-x
^{2}) and the infinite series for it, put the value x = 1/2 and write pi as an infinite series.- Truncate the series after n terms and evaluate the truncated series to get an approximate value of pi. Use the values n=10
^{i}for i=1,2,...,6.- [H] Write a program to determine the smallest positive integer n with the following property. Let
n = a_{k}a_{k-1}...a_{1}a_{0}be the decimal representation of n with

a. Look at the integer:_{k}>0n' = a_{0}a_{k}a_{k-1}...a_{2}a_{1}(the cyclic right shift of n). The desired property of n is that n' must be a proper integral multiple of n.

- [H] Write a program to find the smallest positive integer n with the property that the decimal expansion of 2
^{n}starts with the four digits2005, i.e., 2^{n}= 2005...(Hint: Take log.)