Imports System
Imports System.Collections.Generic
Module EfficientDivisors
'
' Function: FindDivisors
' Purpose: Efficiently find all divisors of a number using the sqrt(n) method.
'
' Explanation:
' - We loop only up to Math.Sqrt(n), which reduces the number of iterations.
' - If i divides n, then both i and n \ i are divisors.
' - If i = n \ i (perfect square), we add it only once.
' - Finally, we sort the list so the divisors appear in ascending order.
'
Function FindDivisors(n As Integer) As List(Of Integer)
Dim divisors As New List(Of Integer)()
Dim limit As Integer = CInt(Math.Sqrt(n))
For i As Integer = 1 To limit
If n Mod i = 0 Then
divisors.Add(i) ' Add the smaller divisor
If i <> n \ i Then
divisors.Add(n \ i) ' Add the paired divisor
End If
End If
Next
divisors.Sort()
Return divisors
End Function
Sub Main()
Dim num As Integer = 24
Dim result As List(Of Integer) = FindDivisors(num)
Console.Write("Divisors of " & num & ": [")
For i As Integer = 0 To result.Count - 1
Console.Write(result(i))
If i < result.Count - 1 Then
Console.Write(", ")
End If
Next
Console.WriteLine("]")
End Sub
End Module
'
' run:
'
' Divisors of 24: [1, 2, 3, 4, 6, 8, 12, 24]
'