1

I recently started reading a book on data structures and it starts off with an introduction in algorithms. In one exercise it asks to prove an algorithm by induction and a loop invariant. The algorithm in pseudocode is:

Algorithm DEC2BIN(int n, int[] b)
Input: int n, array b
Output: b[i] contains the i-th bit of n's binary representation.

1: int x=n, k=0;
2:while(x>0){
3:   b[k]=x%2;
4:   x/=2;
5:   k++;
6:}
en of DEC2BIN

I said:

Let P(n) be the statement "b contains the binary representation of n".

For n=1: It's obvious that b=[1] so, P(1).

Let P(N). How can I show P(n+1)?

Sovengarde
  • 27
  • 1
  • 2
  • 5

1 Answers1

0

Start off by providing a proper loop-invariant. E.g.

"After run k of the loop b will contain the first k digits of the binary representation of n".

Horner's method and Positional Systems should do the trick to prove the statement starting from the above loop-invariant.