Prime factors

This commit is contained in:
VicRen
2020-09-29 17:12:50 +08:00
parent 46f15c3b8d
commit 5ed00d147d
5 changed files with 129 additions and 1 deletions

View File

@@ -1,2 +1,4 @@
# codekata
code kat
This is the code kata for golang.
Code Kata is an attempt to bring this element of practice to software development. A kata is an exercise in karate where you repeat a form many, many times, making little improvements in each.
The intent behind code kata is similar. Each is a short exercise (perhaps 30 minutes to an hour long). Some involve programming, and can be coded in many different ways.

3
go.mod Normal file
View File

@@ -0,0 +1,3 @@
module github.com/vicren/codekata_golang
go 1.13

11
prime_factors/README.md Normal file
View File

@@ -0,0 +1,11 @@
# Prime factors
Prime Numbers kata calculates the prime numbers up to 100.
Example:
The prime numbers to 10 are 2, 3, 5, 7.
Clarifying Notes:
A prime number is a integer which is only divisible by itself and 1.

View File

@@ -0,0 +1,29 @@
package main
import "fmt"
func main() {
fmt.Println("prime number up to 100 is:")
for i := 0; i < 101; i++ {
pf := PrimeFactorsOf(i)
if len(pf) < 2 {
fmt.Println(i)
}
}
}
func PrimeFactorsOf(n int) []int {
ret := make([]int, 0)
divider := 2
for divider < n {
for n%divider == 0 {
ret = append(ret, divider)
n /= divider
}
divider++
}
if n > 1 {
ret = append(ret, n)
}
return ret
}

View File

@@ -0,0 +1,83 @@
package main
import (
"reflect"
"testing"
)
func TestPrimeFactorsOf(t *testing.T) {
tt := []struct {
name string
input int
want []int
}{
{
"prime factors of 1",
1,
[]int{},
},
{
"prime factors of 2",
2,
[]int{2},
},
{
"prime factors of 3",
3,
[]int{3},
},
{
"prime factors of 1",
1,
[]int{},
},
{
"prime factors of 2",
2,
[]int{2},
},
{
"prime factors of 4",
4,
[]int{2, 2},
},
{
"prime factors of 5",
5,
[]int{5},
},
{
"prime factors of 6",
6,
[]int{2, 3},
},
{
"prime factors of 7",
7,
[]int{7},
},
{
"prime factors of 8",
8,
[]int{2, 2, 2},
},
{
"prime factors of 9",
9,
[]int{3, 3},
},
{
"prime factors of a big number",
2 * 2 * 2 * 3 * 3 * 5 * 7 * 11 * 13 * 73,
[]int{2, 2, 2, 3, 3, 5, 7, 11, 13, 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, got %v, want %v", tc.input, got, tc.want)
}
})
}
}