Syncing Changes

This commit is contained in:
Brian Buller 2016-08-29 20:53:59 -05:00
parent 8196643680
commit e63233cad7
2 changed files with 43 additions and 19 deletions

View File

@ -1,29 +1,49 @@
package prime
import (
"fmt"
"strconv"
)
import "fmt"
const testVersion = 2
var sieve []int64
var iter int
func Factors(num int64) []int64 {
var ret []int64
fmt.Println("Factors Called on ", num)
if num == 1 {
return []int64{}
}
for i := range sieve {
if sieve[i] == num {
// It's a prime already in the sieve
return []int64{num}
}
}
ret = []int64{}
for i := int64(2); i <= num; i++ {
fmt.Println("Testing " + strconv.Itoa(int(num)) + "%" + strconv.Itoa(int(i)) + " == " + strconv.Itoa(int(num%i)))
if num%i == 0 {
// It's a factor
ret = append(ret, i)
if num%sieve[i] == 0 {
div := (num / sieve[i])
return append([]int64{sieve[i]}, Factors(div)...)
}
}
return ret
// If we're here, we don't have the prime factors for this number
// Add 1 to the highest prime that we have and find the next prime
i := int64(2)
if len(sieve) > 0 {
i = sieve[len(sieve)-1]
}
fmt.Println(" Looking for a new prime starting at ", i)
for ; i <= num; i++ {
isPrime := true
for j := range sieve {
if i%sieve[j] == 0 {
isPrime = false
}
if !isPrime {
break
}
}
if isPrime {
sieve = append(sieve, i)
// New prime in the sieve, try again
return Factors(num)
}
}
return []int64{}
}

View File

@ -21,10 +21,10 @@ var tests = []struct {
{6, []int64{2, 3}},
{8, []int64{2, 2, 2}},
{9, []int64{3, 3}},
// {27, []int64{3, 3, 3}},
// {625, []int64{5, 5, 5, 5}},
// {901255, []int64{5, 17, 23, 461}},
// {93819012551, []int64{11, 9539, 894119}},
{27, []int64{3, 3, 3}},
{625, []int64{5, 5, 5, 5}},
{901255, []int64{5, 17, 23, 461}},
{93819012551, []int64{11, 9539, 894119}},
}
func TestPrimeFactors(t *testing.T) {
@ -33,8 +33,12 @@ func TestPrimeFactors(t *testing.T) {
}
for _, test := range tests {
fmt.Print("Running Test: ")
fmt.Println(test)
fmt.Print(test)
fmt.Print(" :: ")
actual := Factors(test.input)
fmt.Print(actual)
fmt.Print(" Sieve: ")
fmt.Println(sieve)
if !reflect.DeepEqual(actual, test.expected) {
t.Errorf("prime.Factors(%d) = %v; expected %v",
test.input, actual, test.expected)