1
$\begingroup$

When converting from decimal to binary one of the method is to divide the number by the base (in binary $2$) and write down the number for bottom to the top.

Can we say that the algorithm stops when the number is $1$?

  • 1
    Because one is representable in binary as it is in decimal, not any other number greater than that.2017-02-23
  • 0
    Maybe give an example? I know of an algorithm like that, when you start at $22$ for example, and goes: Dividing by two repeatedly gives you $22$, $11$, $5$, $2$, $1$; now write down $0$ for the even numbers and $1$ for the odd numbers, in reverse order, to get $10110$. Is this the algorithm you're talking about?2017-02-23
  • 0
    @AkivaWeinberger You are right, I will try to be more thorough next time. Yes this is the algorithm2017-02-23

1 Answers 1

1

I would say not; I'd say that the algorithm stops when the number is 0.

For suppose you start with the number 1, and nothing written down.

Then, because the number is 1, you stop.

The end result? You have nothing written down.

For questions like this, it really depends on how you order things. If your stopping condition is at the beginning, you do one thing; if it's at the end, you do another.

Let me clarify by writing it out algorithmically.

ALGORITHM 1

Input: a positive integer n
Output: a sequence of bits representing the number in binary. 
For an input of n = 11, the output should be (1, 0, 1, 1).

Step 0: start with an empty output sequence S = ()
Step 1: if n is 0,  return the sequence S. 
Step 2: divide n by 2 to get k with remainder r; r must be 0 or 1.
Step 3: prepend r onto S. replace n with k. 
Step 4: go to step 1.

Notice that this algorithm does not work for the input $n = 0$, which is why I specified that $n$ should be a positive integer

Here's an alternative algorithm:

ALGORITHM 2

Input: a positive integer n
Output: a sequence of bits representing the number in binary. 
For an input of n = 11, the output should be (1, 0, 1, 1).

Step 0: start with an empty output sequence S = ()
Step 1: divide n by 2 to get k with remainder r; r must be 0 or 1.
Step 2: prepend r onto S. replace n with k. 
Step 3: if n is 1,  return the sequence S. 
Step 4: go to step 1.

Note the difference in testing for termination: we test at the end, and compare $n$ to $1$ as you suggested. In this case, the algorithm fails for all numbers; you'll see this if you hand-simulate for $n = 1$ or $n = 2$, and the reason for the failure will become clear.