Skip to content

Instantly share code, notes, and snippets.

@YuseiUeno
Created September 20, 2018 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YuseiUeno/41da3cfcb1fd995722c53cc4392dd706 to your computer and use it in GitHub Desktop.
Save YuseiUeno/41da3cfcb1fd995722c53cc4392dd706 to your computer and use it in GitHub Desktop.
ユークリッドの互除法
extern crate rand;
use rand::Rng;
fn main() {
let (a, b) = (rand::thread_rng().gen_range(1, 999999999), rand::thread_rng().gen_range(1, 999999999));
println!("gcd {}", gcd(&a, &b)); // ランダムに生成した数値の最大公約数
println!("gcd {}", gcd(&1071, &1029)); // 1071, 1029 の最大公約数 21
}
fn gcd(a: &i32, b: &i32) -> i32 {
println!("a: {}, b: {}", a, b); // 初期値
let (mut a , mut b) = if a > b { (*a, *b) } else { (*b, *a) };
let mut r: i32 = a % b;
while r != 0 {
println!("a: {}, b: {}, r: {}", a, b, r); // 途中の計算結果
a = b;
b = r;
r = a % b;
};
b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment