Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
FindFactors(17, 3)
End Sub
Private Sub FindFactors(ByVal Sum As Integer, ByVal NumberOfFactors As Integer)
Dim Factors(NumberOfFactors + 1) As Integer
Dim i As Integer, j As Integer
For i = 1 To NumberOfFactors Step 1
Factors(i) = 9
Next
Factors(0) = 2
Factors(NumberOfFactors) = 10
Do While Factors(0) = 2
If Factors(1) = 1 Then
Exit Do
End If
For i = 1 To NumberOfFactors Step 1
If Factors(i) = 1 Then
Factors(i - 1) -= 1
For j = i To NumberOfFactors Step 1
Factors(j) = Factors(i - 1)
Next
Exit For
Else
If i = NumberOfFactors Then
Factors(i) -= 1
End If
End If
Next
'Print correct answers
Dim Suggestion As String = ""
Dim AddUp As Integer = 0
For j = 1 To NumberOfFactors Step 1
AddUp = AddUp + Factors(j)
Suggestion = IIf(j = 1, "", Suggestion & "+") & Factors(j)
If j = NumberOfFactors Then
Suggestion = Suggestion & "=" & AddUp
End If
Next
If AddUp = Sum Then
ListBox1.Items.Add(Suggestion)
Application.DoEvents()
End If
Loop
End Sub