This commit is contained in:
2016-08-29 22:24:05 -05:00
parent e63233cad7
commit 36dc090a89
6 changed files with 115 additions and 23 deletions

View File

@@ -1,16 +1,19 @@
package prime
import "fmt"
const testVersion = 2
var sieve []int64
var iter int
func Factors(num int64) []int64 {
fmt.Println("Factors Called on ", num)
if num == 1 {
if len(sieve) == 0 {
sieve = append(sieve, int64(2))
}
switch num {
case 1:
return []int64{}
case 2:
return []int64{2}
}
for i := range sieve {
if sieve[i] == num {
@@ -22,28 +25,26 @@ func Factors(num int64) []int64 {
return append([]int64{sieve[i]}, Factors(div)...)
}
}
// 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++ {
topPrime := sieve[len(sieve)-1]
for i := sieve[0]; i*topPrime <= num; i++ {
// Check if i is a prime
isPrime := true
for j := range sieve {
if i%sieve[j] == 0 {
// Not a prime
isPrime = false
}
if !isPrime {
break
}
}
if isPrime {
// Found a new prime
sieve = append(sieve, i)
// New prime in the sieve, try again
// New data, recurse
return Factors(num)
}
}
return []int64{}
// Is this a prime?
return []int64{num}
}

View File

@@ -3,7 +3,6 @@ package prime
// Return prime factors in increasing order
import (
"fmt"
"reflect"
"testing"
)
@@ -32,13 +31,7 @@ func TestPrimeFactors(t *testing.T) {
t.Fatalf("Found testVersion = %v, want %v", testVersion, targetTestVersion)
}
for _, test := range tests {
fmt.Print("Running 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)