Skip to content

Instantly share code, notes, and snippets.

@BcRikko
Created June 9, 2015 16:51
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 BcRikko/9d20611136adc9be8f72 to your computer and use it in GitHub Desktop.
Save BcRikko/9d20611136adc9be8f72 to your computer and use it in GitHub Desktop.
最大公約数と最小公倍数を表示する(ユークリッドの互除法)
#include <stdio.h>
#include <time.h> // clock用
// 最大公約数の計算(ユークリッドの互除法)
int calcGCD(int in1, int in2)
{
int big, small, r;
// 入力値の大小を判定する
if (in1 < in2)
{
big = in2;
small = in1;
}
else
{
big = in1;
small = in2;
}
while ((r = big % small) != 0)
{
// 余りが0でないなら、bigにsmallを、smallに余りrを代入
big = small;
small = r;
}
// 余りが0なら、smallが最大公約数
return small;
}
// 最小公倍数の計算
int calcLCM(int in1, int in2, int gcd)
{
return (in1 * in2) / gcd;
}
// メイン処理
int main(void){
clock_t start, end;
int in1, in2;
int gcd; // 最大公約数
int lcm; // 最小公倍数
printf("ふたつの値を入力してください。\n");
printf("ひとつ目 >> ");
scanf("%d", &in1);
printf("ふたつ目 >> ");
scanf("%d", &in2);
start = clock();
gcd = calcGCD(in1, in2);
printf("最大公約数は%dです。\n", gcd);
lcm = calcLCM(in1, in2, gcd);
printf("最小公倍数は%dです。\n", lcm);
end = clock();
printf("%d[ms]", end - start);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment