2007年6月20日水曜日

MLで最大公約数 gcd






- fun gcd m n= (* 関数定義 *)
= if m=0 then n else
= if m<=n then gcd m (n - m) else = gcd n (m - n); val gcd = fn : int -> int -> int

- gcd 12 18; (* 評価例 *)
val it = 6 : int
- gcd 60 36;
val it = 12 : int

MLだとこんなに簡単に最大公約数を求める記述ができるのか~ 驚き 感心。ちなみにC言語でユークリッドの互助法を使うとこんな感じ。






/* gcd.c */

#include <stdio.h>

int gcd(int a0,int a1); /* 関数宣言 */

main(){
int a0,a1,temp;

printf("\nThis program gives you
the greatest common divisor of two integers.\n");
/* このプログラムの解説を出力 */

printf("Please input the first integer.\n");
scanf("%d",&a0); /* 一つ目の整数を入力 */

printf("please input the second integer.\n");
scanf("%d",&a1); /* 二つ目の整数を入力 */

if(a0<=0 || a1<=0){ /* 入力が正の数でない時のエラー表示 */
printf("Illegal input");
exit(1);
}
if(a0a1 に調整 */
temp=a0;a0=a1;a1=temp;
}

printf("\nGCD=%d\n",gcd(a0,a1)); /* 結果を出力 */

return 0;
}

int gcd(int a0,int a1){ /* ユークリッドの互除法を使った */
int a,b,temp; /* 最大公約数の計算 */

a=a0;b=a1;
while(b != 0){ /* 互除法を繰り返す */
temp=a%b;a=b;b=temp;
}
return(a);
}



記述量が全然違う。MLってこういうのには向いてるんだな。

0 件のコメント:

コメントを投稿