[Tutor] PYTHON????

Joal Heagney jhe13586 at bigpond.net.au
Thu Sep 1 14:05:02 CEST 2005


luckygoodluck at optonline.net wrote:
> Dear Python,
>  How does a calculator multiply? I want to create a computer software that can multiply. How do I program the computer to multiply? 

Basically the same way you multiply two big numbers on paper, by long 
multiplication.

E.g. Human 24 * 51

   24 *
   51
----
   24   (1 * 24)
120    (5 * 24 and shift one to the left)
----
1224

In order to do long-multiplication, humans need to know the powers from 
1x to 9x, and they have to do carry operations.

However, computers do muliplication in binary, where the only digits are 
0 and 1. Computers don't have to remember times tables.

E.g. Computer 24 * 51

24 in binary is 11000
51 in binary is 110011

How I convert decimal to binary:

What is the bigest power of 2 that is still smaller than the number?
64 > 51 > 32
32 is the largest power.

				Digits from Left
51 / 32 = 1 with 19 remainder     First digit:  1
19 / 16 = 1 with 3 remainder      Second digit: 1
  3 /  8 = 0 with 3 remainder      Third digit:  0
  3 /  4 = 0 with 3 remainder      Fourth digit: 0
  3 /  2 = 1 with 1 remainder      Fifth digit:  1
  1 /  1 = 1 with 0 remainder      Sixth digit:  1

Long Multiplication:

       11000 *
      110011
    --------
       11000  (Multiply 11000 by 1)
      11000   (Multiply 11000 by 1, shift to the left 1)
     00000    (Multiply 11000 by 0, shift to the left 2)
    00000     (Multiply 11000 by 0, shift to the left 3)
   11000      (Multiply 11000 by 1, shift to the left 4)
  11000       (Multiply 11000 by 1, shift to the left 5)
-----------
  1210121000  (My own private representation.)
-----------
  2010201000  (Twos are carried by adding 1 to the left.)
-----------
10011001000  (The binary answer.)

So 11000 * 101001 = 10011001000 in binary

How I convert binary back to decimal:
  1    0   0   1   1    0   0   1   0   0   0
1024 512 256 128  64  32  16   8   4   2   1

1024 + 128 + 64 + 8 = 1228

10011001000 in decimal is 1228

As you can see, the hardest part is the conversion to and from binary to 
decimal.

Joal



More information about the Tutor mailing list