https://slides.com/georgelee/ics141-addition-multiplication/live
We know how to add in base 10. What is the algorithm?
Assume numbers a and b have n digits
carry = 0
d = ""
for i = n - 1 downto 0 # Right to left
sum = a[i] + b[i] + carry
d[i] = sum mod 10
carry = sum / 10
# We also have the carry here
Now that we have an algorithm for adding in base 10, what would the algorithm be for adding in base 2?
Assume numbers a and b have n digits
carry = 0
d = ""
for i = n - 1 downto 1 # Right to left
sum = a[i] + b[i] + carry
d[i] = sum mod 2
carry = sum / 2
# We also have the carry here
Maximum size of a signed 32-bit integer is about 2 billion. What happens when we exceed this?
Things that are approaching or exceeded this limit:
* Gangnam Style
* Twitter post ids (Unsigned)
* IPv4 (Unsigned)
* Unix Time
How large are these numbers?
This algorithm is kinda gnarly. What would this look like at a higher level?
Multiplication in base 2 is actually easy. We need the concept of a left shift, where we add n zeros to the right of the number. We're shifting the number n places. You can also think of it as multiplying by the base.
There is also a right shift, where we bring zeros or ones in from the left.
What would an algorithm look like?
products = []
for i = n - 1 downto 0 # Right to left again.
if b[j] == 1
products[j] = a[j] << (i - n + 1)
else
products[j] = 0
# sum all the values in products.
Computers are only able to handle 1's and 0's. How do we do fractional numbers?
We represent them in "scientific notation".
M x 10e where M = Mantissa and 0 < M < 1 and e = exponent.
A floating point number contains 3 parts.
1 bit for the sign
8 or 11 bits for the exponent
23 or 52 bits for the mantissa
When we typically talk about division with integers, we care about the quotient and the remainder.
The quotient of a divided by b is denoted by "a div b".
The remainder of a divided by b is denoted by "a mod b".
Two numbers are congruent modulo m if
a mod m = b mod m. That is, for an integer k, we have:
a = b + km
And we say a ≡ b (mod m).
Example:
8 mod 12 = 20 mod 12.
Theorem 1:
If a ≡ b (mod m) and c ≡ d (mod m), then:
a + c ≡ b + d (mod m)
a * c ≡ b * d (mod m)
Corollary:
m is a positive integer and a and b be integers. Then:
(a + b) mod m = ((a mod m) + (b mod m)) mod m
(a * b) mod m = ((a mod m) * (b mod m)) mod m
If ac ≡ bc mod m, you may think that a ≡ b, but this is not necessarily true.
Also keep in mind the previous slide.
We can define arithmetic on the set of nonnegative integers less than m.
a +m b = (a + b) mod m
a *m b = (a * b) mod m
Similar to adding time to a clock.
You may have heard of sets, hashes, or dictionaries. Internally, these data structures all use an array.
They determine where to insert data based on hashing functions and modulo arithmetic.