Guest User

Untitled

a guest
Oct 17th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "math"
  6. "sort"
  7. "time"
  8. )
  9.  
  10. func primes(n int) (answer []int) {
  11. bs := make([]bool, n+1)
  12. bs[2] = true
  13. for i := 3; i <= n; i += 2 {
  14. bs[i] = true
  15. }
  16. for i := 3; i*i <= n; i += 2 {
  17. for j := i; i*j <= n; j += 2 {
  18. bs[i*j] = false
  19. }
  20. }
  21. for i, ok := range bs {
  22. if ok {
  23. answer = append(answer, i)
  24. }
  25. }
  26. return
  27. }
  28.  
  29. type ratio struct {
  30. num int
  31. den int
  32. }
  33.  
  34. func (x ratio) float64() float64 {
  35. return float64(x.num) / float64(x.den)
  36. }
  37.  
  38. func (x ratio) isPermutation() (answer bool) {
  39. a, b := x.num, x.den
  40. as, bs := []int{}, []int{}
  41. for a > 0 {
  42. as = append(as, a%10)
  43. a /= 10
  44. }
  45. for b > 0 {
  46. bs = append(bs, b%10)
  47. b /= 10
  48. }
  49. if len(as) != len(bs) {
  50. return
  51. }
  52. sort.Ints(as)
  53. sort.Ints(bs)
  54. for i, v := range as {
  55. if v != bs[i] {
  56. return
  57. }
  58. }
  59. return true
  60. }
  61.  
  62. type rationals []ratio
  63.  
  64. func (xs rationals) max() (answer int) {
  65. min := math.MaxFloat64
  66. for _, x := range xs {
  67. y := x.float64()
  68. if y > min {
  69. continue
  70. }
  71. answer, min = x.num, y
  72.  
  73. }
  74. return
  75. }
  76.  
  77. func find(max int) (answer rationals, ok bool) {
  78. ps := primes(max)
  79. limit := 1e7 / ps[len(ps)-1]
  80. for i := 0; i < len(ps); i++ {
  81. if i < limit {
  82. continue
  83. }
  84. for j := i; j < len(ps); j++ {
  85. if j < limit {
  86. continue
  87. }
  88. n := ps[i] * ps[j]
  89. if n <= limit {
  90. continue
  91. }
  92. if n >= 1e7 {
  93. break
  94. }
  95. r := ratio{n, (ps[i] - 1) * (ps[j] - 1)}
  96. if !r.isPermutation() {
  97. continue
  98. }
  99. answer = append(answer, r)
  100. ok = true
  101. }
  102. }
  103. return
  104. }
  105.  
  106. func problem70() (answer int) {
  107. n := int(math.Sqrt(1e7)) * 2
  108. for n < 1e7 {
  109. if res, ok := find(n); ok {
  110. return res.max()
  111. }
  112. n *= 2
  113. }
  114. return
  115. }
  116.  
  117. func main() {
  118. start := time.Now()
  119. fmt.Println(problem70())
  120. fmt.Println(time.Now().Sub(start).Seconds())
  121. }
Add Comment
Please, Sign In to add comment