How to find the first 4-digit prime number where all digits are unique in VB.NET

1 Answer

0 votes
Imports System

Module Program

    ' Function to check if a number is prime
    Function IsPrime(n As Integer) As Boolean
        If n < 2 Then Return False
        If n Mod 2 = 0 Then Return n = 2

        Dim limit As Integer = CInt(Math.Sqrt(n))
        For i As Integer = 3 To limit Step 2
            If n Mod i = 0 Then Return False
        Next
        Return True
    End Function

    ' Function to check if all digits are unique
    Function HasUniqueDigits(n As Integer) As Boolean
        Dim seen(9) As Boolean  ' track digits 0–9

        While n > 0
            Dim d As Integer = n Mod 10
            If seen(d) Then Return False  ' duplicate found
            seen(d) = True
            n \= 10
        End While
        Return True
    End Function

    Sub Main()
        For num As Integer = 1000 To 9999
            If IsPrime(num) AndAlso HasUniqueDigits(num) Then
                Console.WriteLine($"First 4-digit prime with all unique digits: {num}")
                Return  ' stop after finding the first one
            End If
        Next

        Console.WriteLine("No such number found.")
    End Sub

End Module



' run:
'
' First 4-digit prime with all unique digits: 1039
'

 



answered 19 hours ago by avibootz
...