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

1 Answer

0 votes
package main

import (
    "fmt"
    "math"
)

func isPrime(n int) bool {
    if n < 2 {
        return false
    }
    if n % 2 == 0 {
        return n == 2
    }

    limit := int(math.Sqrt(float64(n)))
    for i := 3; i <= limit; i += 2 {
        if n % i == 0 {
            return false
        }
    }
    
    return true
}

func hasUniqueDigits(n int) bool {
    var seen [10]bool

    for n > 0 {
        d := n % 10
        if seen[d] {
            return false
        }
        seen[d] = true
        n /= 10
    }
    
    return true
}

func main() {
    for num := 1000; num <= 9999; num++ {
        if isPrime(num) && hasUniqueDigits(num) {
            fmt.Printf("First 4-digit prime with all unique digits: %d\n", num)
            return
        }
    }
    fmt.Println("No such number found.")
}



/*
run:

First 4-digit prime with all unique digits: 1039

*/

 



answered 8 hours ago by avibootz
...