FreeBASIC マニュアルのトップに戻る

FreeBASIC 最大公約数と最小公倍数

目次→フォーラム→FreeBASIC→補足Rosetta Code←オリジナル・フォーラム

最大公約数と最小公倍数 左にメニュー・フレームが表示されていない場合は、ここをクリックして下さい

←リンク元に戻る プログラム開発関連に戻る

 ロゼッタ・コードで公開されているコードをベースに、途中経過を可視化するように修正したものです。

 最大公約数(Greatest Common Divisor)は、2つの数に共通する約数「公約数」の中で最も大きいもの。
 最小公倍数(Least Common Multiple)は、2つの数に共通する倍数「公倍数」の中で最も小さいもの。

公約数 ≦ 最大公約数 ≦ 元の数の小さい方 ≦ 元の数の大きい方 ≦ 最小公倍数 ≦ 公倍数


 最大公約数(Greatest Common Divisor)
http://rosettacode.org/wiki/Greatest_common_divisor

'GCD(GreatestCommonDivisor)
'最大公約数
'ユーグリットの互除法

#Include Once "windows.bi"

Function gcd(x As ULongInt, y As ULongInt) As ULongInt
   Dim As ULongInt t
   Dim mojiretsu As String
   mojiretsu = "ユーグリットの互除法の経過"
   Var count = 0
   
   If x < y Then Swap x, y
   While y
      t = y
      count +=1
      mojiretsu = mojiretsu &  Chr(13) & Chr(10)  & "x= " & Str(x) & " ,  y= " & Str(y) & " ,  x Mod y = " & Str(x Mod y)

      y = x Mod y
      x = t
      If count Mod 20 = 0 Then 
         MessageBox (0,mojiretsu,"", MB_OK )
         mojiretsu = ""
      EndIf
   Wend
   MessageBox (0,mojiretsu,"", MB_OK )
   Return x
End Function
 
' ------ 関数を使って計算します ------

Print "GCD( 11111 ,  111111111111111 ) = "; gcd(11111, 111111111111111)
Print "GCD( 11111 ,  111 ) = "; gcd(11111, 111)
Print "GCD( 1029 ,  1071 ) = "; gcd(1071, 1029) '21
Print "GCD( 3510 ,  15438 ) = "; gcd(3510, 15438) '6
Print "GCD( 695 ,  1112 ) = "; gcd(695, 1112) '139
Print "GCD( 286 ,  819 ) = "; gcd(286, 819) '13

Print : Print "何かキーを押すと、終了します"
Sleep

注:MessageBox()の構文
int MessageBox (HWND hWnd , LPCTSTR lpText , LPCTSTR lpCaption , UINT uType)
hWnd - オーナーウィンドウを指定。NULLの場合はオーナーウィンドウを持ちません
lpText - メッセージボックスに表示する文字列
lpCaption - タイトルバーに表示される文字列
uType - メッセージボックスの内容

戻り値 - メッセージボックスの押されたボタンを整数値で返します
このページの先頭に戻る↑ トップページに戻る

 最小公倍数(Least Common Multiple)
http://rosettacode.org/wiki/Least_common_multiple

'Least common multiple
'LCM(LeastCommonMultiple)
'最小公倍数

#Include "vbcompat.bi"
#Include Once "windows.bi"

Function lcm (m As Integer, n As Integer) As Integer
   Dim mojiretsu As String
   mojiretsu = ""
   
   If m = 0 OrElse n = 0 Then Return 0
   If m < n Then Swap m, n '' 必要な反復を最小限に抑えるため
   Var count = 0
   Do
      count +=1
      mojiretsu = mojiretsu &  Chr(13) & Chr(10)  & "count= " & Str(count) & ",  m= " & Str(m)  & ",  m*count= " & Str(m*count) & ",  n= " & Str(n) & ",  Mod= " & Str((m * count) Mod n)

      If count Mod 20 = 0 Then 
         MessageBox (0,mojiretsu,"", MB_OK )
         mojiretsu = ""
      EndIf
   Loop Until (m * count) Mod n  = 0
   MessageBox (0,mojiretsu,"", MB_OK )
   Return m * count
End Function
 
' ------ 関数を使って計算します ------

Print "lcm(12, 18) = "; Format(lcm(12, 18),"#,##0")
Print "lcm(15, 12) = "; Format(lcm(15, 12),"#,##0")
Print "lcm(10, 14) = "; Format(lcm(10, 14),"#,##0")
Print "lcm(1050, 14142) = "; Format(lcm(1050, 14142),"#,##0")
Print
Print "何かキーを押すと、終了します"
Sleep
 
補足 に戻る
←リンク元に戻る プログラム開発関連に戻る
ページ歴史:2020-04-19 作成:2020-04-19
日本語翻訳:WATANABE Makoto

ホームページのトップに戻る

表示-非営利-継承