------------------
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' TextBox1から入力された数値を取得
Dim input = TextBox1.Text.Trim
' 入力が空白または数値でない場合はエラーメッセージを表示
If String.IsNullOrWhiteSpace(input) OrElse Not IsNumeric(input) Then
MessageBox.Show("整数を入力してください。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End If
' 入力された数値を整数に変換
Dim number = Integer.Parse(input)
' 素因数分解を行う
Dim result = Factorize(number)
' 結果をLabel1に表示
Label1.Text = $"素因数分解の結果: {result}"
End Sub
------------------
' 素因数分解する関数
Private Function Factorize(number As Integer) As String
Dim result As String = ""
' 2で割れるだけ割る
While number Mod 2 = 0
result &= "2 "
number = number / 2
End While
' 3以上の奇数で割り続ける
Dim factor As Integer = 3
While factor * factor <= number
If number Mod factor = 0 Then
result &= $"{factor} "
number = number / factor
Else
factor += 2 ' 奇数で試す
End If
End While
' 最後に残った数が素数である
If number > 2 Then
result &= $"{number}"
End If
Return result.Trim()
End Function
------------------
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox1.ResetText()
Label1.ResetText()
End Sub
------------------
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
End
End Sub
End Class
------------------