B4J Question Is there a routine to reduce fractions?

D_Child123

Member
Licensed User
Longtime User
Hi,

Do we have any libraries or snippets, that will take a numerator and a denominator, and reduce them, like reducing 14/42 to 1/3?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Here:
B4X:
Sub AppStart (Form1 As Form, Args() As String)
   Dim nd() As Int = Reduce(300, 360)
   Log($"${nd(0)} / ${nd(1)}"$)
End Sub

Private Sub Reduce(numerator As Int, denominator As Int) As Int()
   Dim g As Int = gcd(numerator, denominator)
   Do While g <> 1
     numerator = numerator / g
     denominator = denominator / g
     g = gcd(numerator, denominator)
   Loop
   Return Array As Int(numerator, denominator)
End Sub

Private Sub gcd(a As Int, b As Int) As Int
   If b = 0 Then Return a
   Return gcd(b, a mod b)
End Sub
 
Upvote 0
Top