Reputation: 1
My code:
Private Sub btnReduce_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReduce.Click
Call Reduce()
End Sub
Function Reduce() As Single
Dim num As Integer = txtNum.Text
Dim deno As Integer = txtDeno.Text
For i = 1 To deno Step +1
If num Mod i = 0 Then
num = num / i
End If
If deno Mod i = 0 Then
deno = deno / i
End If
Next
lblOutputNum.Text = num
lblOutputDeno.Text = deno
End Function
When I enter 2/4 it gives me 1/2. But when I enter 3/6 it gives me 1/1. Does anyone know why it does this? As I can't figure this out. Thanks to anyone who can.
Upvotes: 0
Views: 1487
Reputation: 1
Using Nico's example, I managed to reduce the fraction even further.
For i = 1 To Math.Min(deno, num)/2 Step +1
If num Mod i = 0 And deno Mod i = 0 Then
num = num / i
deno = deno / i
End If
If i > 1 Then
While nume Mod i = 0 And deno Mod i = 0
nume = nume / i
deno = deno / i
End While
End If
Next
Upvotes: 0
Reputation: 32627
You can't divide numerator and denominator independently from each other or you will change the fraction's value:
For i = 1 To Math.Min(deno, num)/2 Step +1
If num Mod i = 0 And deno Mod i = 0 Then
num = num / i
deno = deno / i
End If
Next
Keep in mind that this approach is not very performant. You need to divide numerator and denominator by their greatest common divisor. The GCD can be calculated with the euclidean algorithm.
Upvotes: 2