How to find the largest prime factor of a number in VB.NET

2 Answers

0 votes
Imports System

Module Program
    Function LargestPrimeFactor(ByVal n As Long) As Long
        Dim div As Long = 2
        Dim maxPFact As Long = -1

        While n <> 0
            If n Mod div <> 0 Then
                div += 1
            Else
                maxPFact = n
                n \= div ' Integer division
                If n = 1 Then Exit While
            End If
        End While

        Return maxPFact
    End Function

    Sub Main()
        Dim n As Integer = 124

        Console.WriteLine(LargestPrimeFactor(n)) ' 2 x 2 x 31
        Console.WriteLine(LargestPrimeFactor(288)) ' 2 x 2 x 2 x 2 x 2 x 3 x 3
        Console.WriteLine(LargestPrimeFactor(1288)) ' 2 x 2 x 2 x 7 x 23
        Console.WriteLine(LargestPrimeFactor(100000000)) ' 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5
    End Sub
End Module


' run:
'
' 31
' 3
' 23
' 5
'

 



answered Apr 16, 2025 by avibootz
0 votes
Imports System

Public Class MainClass

    ' Returns the largest prime factor of n
    Public Shared Function LargestPrimeFactor(n As Long) As Long

        Dim largest As Long = -1

        ' Step 1: Remove all factors of 2
        While n Mod 2 = 0
            largest = 2
            n \= 2
        End While

        ' Step 2: Try odd factors from 3 to sqrt(n)
        Dim i As Long = 3
        While i * i <= n
            While n Mod i = 0
                largest = i
                n \= i
            End While
            i += 2
        End While

        ' Step 3: If n is still > 2, it is a prime number
        If n > 2 Then
            largest = n
        End If

        Return largest
    End Function

    Public Shared Sub Main(args As String())

        Dim n1 As Integer = 124 ' 2 x 2 x 31
        Dim n2 As Integer = 288 ' 2 x 2 x 2 x 2 x 2 x 3 x 3
        Dim n3 As Integer = 1288 ' 2 x 2 x 2 x 7 x 23
        Dim n4 As Integer = 100000000 ' 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5
        Dim n5 As Long = 600851475143 ' 71, 893, 1471, 6857

        Console.WriteLine("Largest prime factor: " & LargestPrimeFactor(n1))
        Console.WriteLine("Largest prime factor: " & LargestPrimeFactor(n2))
        Console.WriteLine("Largest prime factor: " & LargestPrimeFactor(n3))
        Console.WriteLine("Largest prime factor: " & LargestPrimeFactor(n4))
        Console.WriteLine("Largest prime factor: " & LargestPrimeFactor(n5))

    End Sub

End Class



' run:
'
' Largest prime factor: 31
' Largest prime factor: 3
' Largest prime factor: 23
' Largest prime factor: 5
' Largest prime factor: 6857
' 

 



answered 1 hour ago by avibootz
...