k.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package kata
  2. import (
  3. "fmt"
  4. "math"
  5. "strings"
  6. )
  7. /*
  8. trimPrimes removes the impossible primes from the list against which to check.
  9. - primes: the current list
  10. - low: the lowest possible value for a valid prime
  11. - n: the maximum possible value for a valid prime
  12. */
  13. func trimPrimes(primes []int, low, high int) []int {
  14. var res []int
  15. lowIndex, highIndex := 0, int(math.Ceil(math.Sqrt(float64(high))))
  16. for i, prime := range primes {
  17. if prime < low {
  18. lowIndex = i
  19. }
  20. if prime > highIndex {
  21. highIndex = i
  22. break
  23. }
  24. }
  25. if highIndex > len(primes) {
  26. res = primes[lowIndex:]
  27. } else {
  28. res = primes[lowIndex:highIndex]
  29. }
  30. return res
  31. }
  32. func trialDivision(n int) []int {
  33. limit := int(math.Ceil(math.Sqrt(float64(n))))
  34. primes := Primes(limit)
  35. var divisors []int
  36. for _, prime := range primes {
  37. for n > 1 {
  38. if n%prime == 0 {
  39. divisors = append(divisors, prime)
  40. n /= prime
  41. primes = trimPrimes(primes, prime, n)
  42. continue
  43. }
  44. primes = trimPrimes(primes, prime+2, n)
  45. break
  46. }
  47. }
  48. if n > 1 {
  49. divisors = append(divisors, n)
  50. }
  51. return divisors
  52. }
  53. func format(curr, power int) string {
  54. if power == 1 {
  55. return fmt.Sprintf("(%d)", curr)
  56. } else {
  57. return fmt.Sprintf("(%d**%d)", curr, power)
  58. }
  59. }
  60. func PrimeFactors(n int) string {
  61. if n <= 1 {
  62. return ""
  63. }
  64. factors := trialDivision(n)
  65. var rows []string
  66. curr := 1
  67. power := 1
  68. for _, divisor := range factors {
  69. if divisor == curr {
  70. power++
  71. } else {
  72. rows = append(rows, format(curr, power))
  73. curr = divisor
  74. power = 1
  75. }
  76. }
  77. rows = append(rows, format(curr, power))
  78. res := strings.Join(rows[1:], "")
  79. return res
  80. }