Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,235 questions

56,138 answers

573 users

How to find all divisors of a number in VB.NET

1 Answer

0 votes
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]
'

 



answered Jul 1, 2020 by avibootz
edited Jul 1 by avibootz
...