From 3513724df0310e8f414f7b145ec6be7d200bfd72 Mon Sep 17 00:00:00 2001 From: VicRen Date: Sun, 22 Nov 2020 23:09:18 +0800 Subject: [PATCH] 49: prime permutations --- 49_prime_permutations/main.go | 50 ++++++++++++++++++++++++++++++ 49_prime_permutations/main_test.go | 38 +++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 49_prime_permutations/main.go create mode 100644 49_prime_permutations/main_test.go diff --git a/49_prime_permutations/main.go b/49_prime_permutations/main.go new file mode 100644 index 0000000..3effc52 --- /dev/null +++ b/49_prime_permutations/main.go @@ -0,0 +1,50 @@ +package main + +import "fmt" + +func main() { + for a := 1489; a < 3340; a++ { + b := a + 3330 + c := b + 3330 + if isPrime(a) && isPrime(b) && isPrime(c) && isPerm(a, b) && isPerm(b, c) { + fmt.Println((a*10000+b)*10000 + c) + } + } +} + +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 isPerm(a, b int) bool { + cnt := []int{0, 0, 0, 0, 0, 0, 0, 0, 0, 0} + for a > 0 { + cnt[a%10]++ + a = a / 10 + } + for b > 0 { + cnt[b%10]-- + b = b / 10 + } + for _, n := range cnt { + if n != 0 { + return false + } + } + return true +} diff --git a/49_prime_permutations/main_test.go b/49_prime_permutations/main_test.go new file mode 100644 index 0000000..4d85553 --- /dev/null +++ b/49_prime_permutations/main_test.go @@ -0,0 +1,38 @@ +package main + +import "testing" + +func Test_isPerm(t *testing.T) { + type args struct { + a int + b int + } + tests := []struct { + name string + args args + want bool + }{ + { + "test_1", + args{123, 321}, + true, + }, + { + "test_2", + args{123, 213}, + true, + }, + { + "test_3", + args{123, 211}, + false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := isPerm(tt.args.a, tt.args.b); got != tt.want { + t.Errorf("isPerm() = %v, want %v", got, tt.want) + } + }) + } +}