package prime

const testVersion = 2

var sieve []int64
var iter int

func Factors(num int64) []int64 {
	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 {
			// It's a prime already in the sieve
			return []int64{num}
		}
		if num%sieve[i] == 0 {
			div := (num / sieve[i])
			return append([]int64{sieve[i]}, Factors(div)...)
		}
	}

	// If we're here, we don't have the prime factors for this number
	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
				break
			}
		}
		if isPrime {
			// Found a new prime
			sieve = append(sieve, i)
			// New data, recurse
			return Factors(num)
		}
	}
	// Is this a prime?
	return []int64{num}
}
