Skip to content

Instantly share code, notes, and snippets.

@ChunMinChang
Last active January 16, 2019 06:43
Show Gist options
  • Save ChunMinChang/fb0cf3e89ae4b5f4beae772463ca06f1 to your computer and use it in GitHub Desktop.
Save ChunMinChang/fb0cf3e89ae4b5f4beae772463ca06f1 to your computer and use it in GitHub Desktop.
Compute X * Y without arithmetical operators
fn main() {
println!("123 * 345 = {}", multiply(123, 345));
}
fn multiply(mut a: u32, mut b: u32) -> u32 {
let mut sum = 0;
while a != 0 {
if a & 1 == 1 {
sum = add(sum, b);
}
a >>= 1;
b <<= 1;
}
sum
}
// fn add(x: u32, y: u32) -> u32 {
// if x == 0 || y == 0 {
// return x | y;
// }
// let sum = x ^ y;
// let carry = (x & y) << 1;
// add(sum, carry)
// }
fn add(mut sum: u32, mut carry: u32) -> u32 {
while carry != 0 {
let next_carry = (sum & carry) << 1;
sum ^= carry;
carry = next_carry;
}
sum
}
#[test]
fn test_add_without_overflow() {
assert_eq!(add(0, 41), 41);
assert_eq!(add(43, 0), 43);
assert_eq!(add(131, 37), 131 + 37);
}
#[test]
fn test_multiply_without_overflow() {
assert_eq!(multiply(0, 41), 0);
assert_eq!(multiply(43, 0), 0);
assert_eq!(multiply(131, 37), 131 * 37);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment