Crates.io | gcd-bitwise |
lib.rs | gcd-bitwise |
version | 0.3.0 |
source | src |
created_at | 2021-08-25 14:37:52.017704 |
updated_at | 2021-08-30 20:34:59.370655 |
description | The binary Euclidean algorithm for computing gcd. |
homepage | |
repository | https://github.com/Inoshy/rust-book-helper/tree/master/problems/gcd-bitwise |
max_upload_size | |
id | 442188 |
size | 6,164 |
Disclaimer: The code is not mine.
The underlying code is part of the coreutils project. I have forked it for ease of use, for those who dont want to pull in big dependencies. I modified some parts for general use cases, eg. implementing generic types. This crate is dependency free.
numeric types of arguments will be cast to usize
instead of u32
from now.
You can pass u8
, u16
, u32
, u64
and usize
numeric types into gcd()
function. But please note that the 2 numbers that you pass must have the same type. Passing any signed type (like i32
) may give unexpected results. Please have a look at the Quick Start section below for examples.
This code uses stein's algorithm, that replaces division with arithmetic shifts, comparisons, and subtraction, for optimization of performance. For more info please refer to this page.
use gcd_bitwise::interface::gcd;
fn main() {
// For `u8` type
let num1: u8 = 15;
let num2: u8 = 51;
let gcd: u8 = gcd(num1, num2);
println!("gcd: {}", gcd); // 3
// For `usize` type
let num1: usize = 65535;
let num2: usize = 125;
let gcd: usize = gcd(num1, num2);
println!("gcd: {}", gcd); // 5
// And on it goes...
}
Final Note:
If you find any problems dont hesitate to open an issue on github.