p060.scm 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. ;; Prime pair sets
  2. ;; We want a vector of primes with lst of pairs
  3. (define-module (unsolved p060))
  4. (use-modules (euler primes)
  5. (euler utils)
  6. (srfi srfi-1))
  7. (define-public (n-prime-pair-sets n)
  8. (define prime-pairs (make-prime-pairs 50000))
  9. (define (get-pair-set i)
  10. (let lp ([candidate-set (array-ref prime-pairs i)] [acc (list i)])
  11. (if (null? candidate-set) acc
  12. (let* ([candidate-pairs (array-ref prime-pairs (car candidate-set))]
  13. [new-candidates (lset-intersection = candidate-pairs
  14. candidate-set)]
  15. [acc-intersection (lset-intersection = acc candidate-pairs)])
  16. (if (and (equal? acc acc-intersection))
  17. (lp new-candidates (cons (car candidate-set) acc))
  18. (lp (cdr candidate-pairs) acc))))))
  19. (let lp ([i 3])
  20. (cond
  21. [(> i 100) '()]
  22. [(not (array-ref prime-pairs i)) (lp (1+ i))]
  23. [else
  24. (let ([pair-set (get-pair-set i)])
  25. (if (>= (length pair-set) n)
  26. pair-set
  27. (lp (1+ i))))])))
  28. (define prime-size (expt 10 8))
  29. (define prime-bitvector (erato-bit prime-size))
  30. ;; TODO: figure out how to use do instead of traditional loop
  31. (define (make-prime-pairs n)
  32. (define primes (take-while (lambda (prime) (< prime n))
  33. (prime-bitvector->lst prime-bitvector)))
  34. (define prime-pairs
  35. (let ([prime-pairs (make-vector (1+ n) #f)])
  36. (array-index-map! prime-pairs
  37. (lambda (i)
  38. (if (array-ref prime-bitvector i) '() #f)))
  39. prime-pairs))
  40. (let lp ([primes1 primes] [primes2 primes])
  41. (cond
  42. [(null? primes1) (reverse-pairs prime-pairs)]
  43. [(null? primes2) (lp (cdr primes1) primes)]
  44. [else
  45. (let* ([prime1 (car primes1)] [prime2 (car primes2)]
  46. [prepend-num (number-append prime1 prime2)]
  47. [postpend-num (number-append prime2 prime1)])
  48. (when (and
  49. (< prepend-num prime-size)
  50. (< prepend-num prime-size)
  51. (array-ref prime-bitvector
  52. prepend-num)
  53. (array-ref prime-bitvector
  54. postpend-num))
  55. (array-set! prime-pairs
  56. (cons prime2
  57. (array-ref prime-pairs
  58. prime1))
  59. prime1))
  60. (lp primes1 (cdr primes2)))])))
  61. (define (reverse-pairs prime-pairs)
  62. (array-map! prime-pairs
  63. (lambda (pairs)
  64. (if pairs
  65. (reverse pairs)
  66. pairs))
  67. prime-pairs)
  68. prime-pairs)