How to find two prime numbers that, when concatenated, form another prime number in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Module PrimeConcat

    ' Function to check primality
    Function IsPrime(n As Long) As Boolean
        If n < 2 Then Return False
        If n Mod 2 = 0 AndAlso n <> 2 Then Return False

        Dim i As Long = 3
        While i * i <= n
            If n Mod i = 0 Then Return False
            i += 2
        End While

        Return True
    End Function

    ' Concatenate two integers
    Function Concat(a As Integer, b As Integer) As Long
        Dim s As String = a.ToString() & b.ToString()
        Return Long.Parse(s)
    End Function

    Sub Main()
        Dim limit As Integer = 12 ' you can increase this
        Dim primes As New List(Of Integer)()

        ' Generate primes up to limit
        For i As Integer = 2 To limit
            If IsPrime(i) Then
                primes.Add(i)
            End If
        Next

        ' Check pairs
        For i As Integer = 0 To primes.Count - 1
            For j As Integer = 0 To primes.Count - 1
                If i = j Then Continue For ' skip same prime if you want
                Dim num As Long = Concat(primes(i), primes(j))
                If IsPrime(num) Then
                    Console.WriteLine($"{primes(i)} + {primes(j)} -> {num} is prime")
                End If
            Next
        Next
    End Sub

End Module


	
' run:
'
' 2 + 3 -> 23 is prime
' 2 + 11 -> 211 is prime
' 3 + 7 -> 37 is prime
' 3 + 11 -> 311 is prime
' 5 + 3 -> 53 is prime
' 7 + 3 -> 73 is prime
' 11 + 3 -> 113 is prime
' 

 



answered 14 hours ago by avibootz
...