Exercises 1
Exercises 1
Exercises 1
1
4. Design an algorithm for computing ⌊ √ n ⌋ for any positive integer n. Besides
assignment and comparison, your algorithm may only use the four basic
arithmetical operations.
int sqroot(int n)
{ int i, m, p;
p = 1;
for(i=2; i < 100; i++)
{ m = i*i;
if( m > n) break;
p = m;
}
return p/i+1;
}
5. Design an algorithm to find all the common elements in two sorted lists of numbers.
For example, for the lists 2, 5, 5, 5 and 2, 2, 3, 5, 5, 7, the output should be 2, 5, 5.
What is the maximum number of comparisons your algorithm makes if the lengths
of the two given lists are m and n, respectively?
#include <stdio.h>
void commonEle(int a[], int m, int b[], int n)
{ int i, j;
for(i=0; i < m; i++)
for(j=0; j < n; j++)
if(a[i] == b[j])
{ printf(" %d ", a[i]);
i++; j++;
}
}
int main()
{ int a[4] = {2, 5, 5, 5};
int b[6] = {2, 2, 3, 5, 5, 7};
commonEle(a, 4, b, 6);
return 0;
}
The maximum number of comparisons your algorithm makes if the lengths of
the two given lists are m and n, respectively?
Ans: m*n
1
7. Prove the equality gcd(m, n) = gcd(n, m mod n) for every pair of positive
integers m and n.
For any pair of positive integers m and n, if d divides both m and n, it also
divides both n and r = m mod n = m−qn. Similarly, if d divides both n and
r = m mod n = m − qn, it also divides both m = r + qn and n. Thus, the two pairs
(m, n) and (n, r) have the same finite nonempty set of common divisors,
including the largest element in the set, i.e., gcd(m, n) = gcd(n, r).
Exercises 1.2
1. Describe the standard algorithm for finding the binary representation of a positive
decimal integer.
void binary(int n)
{ if( n > 1 )
binary(n/2);
printf("%d ", n%2);
}
.
9. Consider the following algorithm for finding the distance between the two closest
elements in an array of numbers.
2
Exercises 1.3
1. Consider the algorithm for the sorting problem that sorts an array by counting, for
each of its elements, the number of smaller elements and then uses this
information to put the element in its appropriate position in the sorted array:
a. Apply this algorithm to sorting the list 60, 35, 81, 98, 14, 47.
b. Is this algorithm stable?
c. Is it in-place?