From 34030a6503ff67b5e4fa24fcd4f80b292df85d85 Mon Sep 17 00:00:00 2001 From: VicRen Date: Fri, 17 Sep 2021 11:51:17 +0800 Subject: [PATCH] prime factor 210917 --- prime_factors_210917/main_test.go | 50 +++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 prime_factors_210917/main_test.go diff --git a/prime_factors_210917/main_test.go b/prime_factors_210917/main_test.go new file mode 100644 index 0000000..aa59d03 --- /dev/null +++ b/prime_factors_210917/main_test.go @@ -0,0 +1,50 @@ +package main + +import ( + "reflect" + "testing" +) + +func TestPrimeFactorsOf(t *testing.T) { + tt := []struct { + name string + input int + want []int + }{ + {"1", 1, []int{}}, + {"2", 2, []int{2}}, + {"3", 3, []int{3}}, + {"4", 4, []int{2, 2}}, + {"5", 5, []int{5}}, + {"6", 6, []int{2, 3}}, + {"7", 7, []int{7}}, + {"8", 8, []int{2, 2, 2}}, + {"9", 9, []int{3, 3}}, + {"a very large number", 2 * 5 * 17 * 37 * 71 * 73, []int{2, 5, 17, 37, 71, 73}}, + } + + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + got := PrimeFactorsOf(tc.input) + if !reflect.DeepEqual(got, tc.want) { + t.Errorf("PrimeFactorsOf %d = %v, want %v", tc.input, got, tc.want) + } + }) + } +} + +func PrimeFactorsOf(n int) []int { + ret := make([]int, 0) + d := 2 + for d < n { + for n % d == 0 { + ret = append(ret, d) + n /= d + } + d++ + } + if n > 1 { + ret = append(ret, n) + } + return ret +}