Adding and Subtracting Mixed Numbers And Multiplying Fractions
Adding numbers without using the + operator
Transcript of Adding numbers without using the + operator
Adding Numbers
High Level Languages
• Java
• C#
• Haskell
High Level Languages
• c
* seriously
Syntactic Sugar
• + operator
Bitwise Operators
• ‘AND’ - takes two binary inputs. Returns 1 if both are 1, otherwise 0
0 and 0 -‐-‐> 0 0 and 1 -‐-‐> 0 1 and 0 -‐-‐> 0 1 and 1 -‐-‐> 1
Bitwise Operators
• ‘XOR’ - Exclusive OR. Returns 1 if one or the other inputs is 1, but not neither and not both.
0 xor 0 -‐-‐> 0 0 xor 1 -‐-‐> 1 1 xor 0 -‐-‐> 1 1 xor 1 -‐-‐> 0
Bit Shifting
• Left-shift - moves all the 1’s across to the left
0001 0110 (22) -‐> 0010 1100 (44)
• Right-shift - moves all the 1’s across to the right
0001 0110 (22) -‐> 0000 1011 (11)
The Formula
• Start with two numbers: x and y
set a = (x AND y) set b = (x XOR y) set x = a left-shifted by 1 set y = b -- keep going until a is 0. The answer is b
E.G. 10 + 7
1010 & 0111 -‐-‐-‐-‐ 0010 -‐> Left-‐shifted -‐> 0100 (4)
1010 ^ 0111 -‐-‐-‐-‐ 1101 (13)
E.G. 4 + 13
0100 & 1101 -‐-‐-‐-‐ 0100 -‐> Left-‐shifted -‐> 1000 (8)
0100 ^ 1101 -‐-‐-‐-‐ 1001 (9)
E.G. 8 + 9
1000 & 1001 -‐-‐-‐-‐ 1000 -‐> Left-‐shifted -‐> 10000 (16)
1000 ^ 1001 -‐-‐-‐-‐ 0001 (1)
E.G. 16 + 1
10000 & 00001 -‐-‐-‐-‐ 00000 -‐> Left-‐shifted -‐> 00000 (0)
10000 ^ 00001 -‐-‐-‐-‐ 10001 (17)
Adding Numbers in C
int add(int x, int y) { int a,b; do { a = x & y; b = x ^ y; x = a << 1; y = b; } while (a); return b; }
recursion!
int add(int x, int y) { int a,b; if (x == 0) return y;
a = (x & y) << 1; b = x ^ y; return add(a, b); }
recursion!
int add(int x, int y) { if (x == 0) return y;
return add((x & y) << 1, x ^ y); }
just for fun...
import Data.Bits
add :: (Bits a) => a -‐> a -‐> a add a b | a == 0 = b | otherwise = add ((a .&. b) `shiftL` 1) (a `xor` b)
https://gist.github.com/IanRandall/6775842