exercism/go/prime-factors/prime.go

51 lines
926 B
Go
Raw Normal View History

2016-08-23 20:47:19 +00:00
package prime
const testVersion = 2
2016-08-25 17:17:37 +00:00
var sieve []int64
2016-08-30 01:53:59 +00:00
var iter int
2016-08-25 17:17:37 +00:00
func Factors(num int64) []int64 {
2016-08-30 03:24:05 +00:00
if len(sieve) == 0 {
sieve = append(sieve, int64(2))
}
switch num {
case 1:
2016-08-30 01:53:59 +00:00
return []int64{}
2016-08-30 03:24:05 +00:00
case 2:
return []int64{2}
2016-08-30 01:53:59 +00:00
}
2016-08-25 17:17:37 +00:00
for i := range sieve {
if sieve[i] == num {
2016-08-30 01:53:59 +00:00
// It's a prime already in the sieve
2016-08-25 17:17:37 +00:00
return []int64{num}
}
2016-08-30 01:53:59 +00:00
if num%sieve[i] == 0 {
div := (num / sieve[i])
return append([]int64{sieve[i]}, Factors(div)...)
}
2016-08-25 17:17:37 +00:00
}
2016-08-30 03:24:05 +00:00
2016-08-30 01:53:59 +00:00
// If we're here, we don't have the prime factors for this number
2016-08-30 03:24:05 +00:00
topPrime := sieve[len(sieve)-1]
for i := sieve[0]; i*topPrime <= num; i++ {
// Check if i is a prime
2016-08-30 01:53:59 +00:00
isPrime := true
for j := range sieve {
if i%sieve[j] == 0 {
2016-08-30 03:24:05 +00:00
// Not a prime
2016-08-30 01:53:59 +00:00
isPrime = false
break
}
}
if isPrime {
2016-08-30 03:24:05 +00:00
// Found a new prime
2016-08-30 01:53:59 +00:00
sieve = append(sieve, i)
2016-08-30 03:24:05 +00:00
// New data, recurse
2016-08-30 01:53:59 +00:00
return Factors(num)
2016-08-23 20:47:19 +00:00
}
}
2016-08-30 03:24:05 +00:00
// Is this a prime?
return []int64{num}
2016-08-23 20:47:19 +00:00
}