mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-24 19:54:43 +01:00
41: pandigital prime
This commit is contained in:
49
41_pandigital_prime/main.go
Normal file
49
41_pandigital_prime/main.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
for i := 987654321; i > 1; i-- {
|
||||
if !isPandigital(strconv.Itoa(i)) {
|
||||
continue
|
||||
}
|
||||
fmt.Println(i)
|
||||
if isPrime(i) {
|
||||
fmt.Println("largest pandigital prime:", i)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isPrime(n int) bool {
|
||||
if n <= 1 {
|
||||
return false
|
||||
}
|
||||
res := n
|
||||
//牛顿法求平方根
|
||||
for res*res > n {
|
||||
res = (res + n/res) / 2
|
||||
}
|
||||
divider := 2
|
||||
for divider <= res {
|
||||
if n%divider == 0 {
|
||||
return false
|
||||
}
|
||||
divider++
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func isPandigital(s string) bool {
|
||||
l := len(s)
|
||||
for i := 1; i <= l; i++ {
|
||||
if !strings.Contains(s, strconv.Itoa(i)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
37
41_pandigital_prime/main_test.go
Normal file
37
41_pandigital_prime/main_test.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func Test_isPandigital(t *testing.T) {
|
||||
type args struct {
|
||||
s string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
"912345678",
|
||||
args{"912345678"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"12345678",
|
||||
args{"12345678"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"812349756",
|
||||
args{"812349756"},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := isPandigital(tt.args.s); got != tt.want {
|
||||
t.Errorf("isPandigital() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user