solution.scm 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. ;; https://projecteuler.net/problem=26
  2. ;; Reciprocal cycles
  3. ;; Problem 26
  4. ;; A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
  5. ;; 1/2 = 0.5
  6. ;; 1/3 = 0.(3)
  7. ;; 1/4 = 0.25
  8. ;; 1/5 = 0.2
  9. ;; 1/6 = 0.1(6)
  10. ;; 1/7 = 0.(142857)
  11. ;; 1/8 = 0.125
  12. ;; 1/9 = 0.(1)
  13. ;; 1/10 = 0.1
  14. ;; Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
  15. ;; Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
  16. (import
  17. (except (rnrs base) let-values map)
  18. (only (guile)
  19. lambda* λ)
  20. (ice-9 match)
  21. (contract)
  22. (prefix (lib math) math:)
  23. (lib print-utils))
  24. (define-with-contract find-longest-repeating-decimals
  25. (require (integer? limit)
  26. (positive? limit)
  27. (> limit 1))
  28. (ensure (positive? <?>)
  29. (integer? <?>))
  30. (λ (limit)
  31. (let iter ([max-denom 1] [max-length 0] [denom 1])
  32. (let ([current-length
  33. (math:rational-repeating-decimals-length (/ 1 denom))])
  34. (cond
  35. [(>= denom limit)
  36. max-denom]
  37. [(> current-length max-length)
  38. (iter denom current-length (+ denom 1))]
  39. [else
  40. (iter max-denom max-length (+ denom 1))])))))
  41. (simple-format
  42. (current-output-port)
  43. "denominator with longest recurring cycle in decimals: ~a\n"
  44. (find-longest-repeating-decimals 1000))