Microsoft Small Basic

Program Listing: TQX303
' Reduce a fraction to a common denominator 0.1
' Copyright (c) 2013 Nonki Takahashi. All rights reserved.
'
' History:
' 0.1 2013-11-28 Created.
'
While "True"
TextWindow.Write("Fraction (ex. 4/6) ? ")
buf = TextWindow.Read()
ptr = 1
ParseFrac()
If match Then
Math_GCM() ' greatest common measure
If number2 = gcm Then
TextWindow.WriteLine("= " + (number1 / gcm))
Else
TextWindow.Write("= " + (number1 / gcm))
TextWindow.WriteLine("/" + (number2 / gcm))
EndIf
EndIf
EndWhile
Sub ParseFrac
' param buf - buffer including fraction
' param ptr - buffer pointer (incleased if match)
' return number1 - numerator
' return number2 - denominator
' return match - "True" if fraction both numerator and denominator are natural numbers
ParseNum()
If match Then
number1 = number
ParseSlash()
EndIf
If match Then
ParseNum()
EndIf
If match Then
number2 = number
EndIf
EndSub
Sub ParseNum
' param buf - buffer including number
' param ptr - buffer pointer (incleased if match)
' return number - natural number
' return match - "True" if natural number
match = "False"
number = ""
n = Text.GetSubText(buf, ptr, 1)
While Text.IsSubText("0123456789", n)
match = "True"
number = Text.Append(number, n)
ptr = ptr + 1
n = Text.GetSubText(buf, ptr, 1)
EndWhile
EndSub
Sub ParseSlash
' param buf - buffer including slash "/"
' param ptr - buffer pointer (incleased if match)
' return match - "True" if slash
If Text.GetSubText(buf, ptr, 1) = "/" Then
match = "True"
ptr = ptr + 1
Else
match = "False"
EndIf
EndSub
Sub Math_GCM
' param number1
' param number2
' return gcm - great common measure
number = number1
Math_CM()
cm1 = cm
ncm1 = ncm
number = number2
Math_CM()
For j = ncm To 1 Step -1
For i = ncm1 To 1 Step -1
If cm1[i] = cm[j] Then
gcm = cm[j]
Goto break
EndIf
EndFor
EndFor
break:
EndSub
Sub Math_CM
' param number
' return cm[] - common measures
' return ncm - number of common measures
cm = ""
ncm = 0
For n = 1 To Math.SquareRoot(number)
If Math.Remainder(number, n) = 0 Then
ncm = ncm + 1
cm[ncm] = n
EndIf
EndFor
half = ncm
For i = half To 1 Step -1
n = number / cm[i]
If n <> ncm[i] Then
ncm = ncm + 1
cm[ncm] = n
EndIf
EndFor
'DumpCM()
EndSub
Sub DumpCM
TextWindow.Write("Common measures of " + number + " are ")
For i = 1 To ncm
TextWindow.Write(cm[i])
If i < ncm Then
TextWindow.Write(", ")
EndIf
EndFor
TextWindow.WriteLine(".")
EndSub