Integer Square-root by Lo-o-o-o-o-o-o

advertisement
CSL101: Introduction to Computers and Programming
I semester 2006-07
Integer Square-root by Lo-o-o-o-o-o-o-ng division
A method for computing the integer square-root of a positive integer is illustrated by an example below. If you
have learnt it before you should be able to understand the example. If you haven’t learnt, now is a good time
to figure out and learn it! The example gives snapshots of the computation of the integer square root of the
number 8381029. It procceeds as follows:
_____________
| 8 38 10 29
2
_____________
2 | 8 38 10 29
| 4
2
_____________
2 | 8 38 10 29
| 4
| __
| 4
2
_____________
2 | 8 38 10 29
| 4
| __
4 | 4 38
2 8
_____________
2 | 8 38 10 29
| 4
| __
48 | 4 38
| 3 84
2 8
_____________
2 | 8 38 10 29
| 4
| __
48 | 4 38
| 3 84
| ____
|
54
2 8
_____________
2 | 8 38 10 29
| 4
| __
48 | 4 38
| 3 84
| ____
56 |
54 10
2 8 9
_____________
2 | 8 38 10 29
| 4
| __
48 | 4 38
| 3 84
| ____
569 |
54 10
|
51 21
2 8 9
_____________
2 | 8 38 10 29
| 4
| __
48 | 4 38
| 3 84
| ____
569 |
54 10
|
51 21
|
_____
|
2 89
2 8 9
_____________
2 | 8 38 10 29
| 4
| __
48 | 4 38
| 3 84
| ____
569 |
54 10
|
51 21
|
_____
|
2 89 29
2 8 9
_____________
2 | 8 38 10 29
| 4
| __
48 | 4 38
| 3 84
| ____
569 |
54 10
|
51 21
|
_____
578
|
2
48
569
5785
2 89 29
2 8 9 5
_____________
| 8 38 10 29
| 4
| __
| 4 38
| 3 84
| ____
|
54 10
|
51 21
|
_____
|
2 89 29
|
2 89 25
|
_______
|
4
√
and yields b 8381029c = 2895.
What you have to do
1. Formalize the method as an algorithm using the Top-down development technique and prove the correctness
of your algorithm.
2. How will you formalize the “guesswork” that is involved in the algorithm?
3. Assume that non-negative integers are represented as lists of digits with
(a) the empty list denoting 0 and
(b) any nonempty list of digits [dn , dn−1 , . . . , d0 ] denoting the number 10n dn + 10n−1 dn−1 + · · · + d0
4. Write an ML program to compute the non-negative integer square-root of an arbitrarily large nonnegative integer, where the
Input is a string of digits e.g.‘‘08310294562908719012’’.
explode, implode are functions used to convert between strings and lists of characters.
Output is a string of digits representing the integer square-root of the given input number.
given as a string of digits.
Download