solution.scm 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. ;; https://projecteuler.net/problem=29
  2. ;; Consider all integer combinations of a^b for
  3. ;; 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5
  4. ;; :
  5. ;; 2^2=4, 2^3=8, 2^4=16, 2^5=32
  6. ;; 3^2=9, 3^3=27, 3^4=81, 3^5=243
  7. ;; 4^2=16, 4^3=64, 4^4=256, 4^5=1024
  8. ;; 5^2=25, 5^3=125, 5^4=625, 5^5=3125
  9. ;; If they are then placed in numerical order, with any repeats
  10. ;; removed, we get the following sequence of 15 distinct terms:
  11. ;; 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024,
  12. ;; 3125
  13. ;; How many distinct terms are in the sequence generated by ab
  14. ;; for
  15. ;; 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100
  16. ;; ?
  17. (import
  18. (except (rnrs base) let-values map)
  19. (only (guile)
  20. lambda* λ)
  21. (srfi srfi-69) ; hash tables
  22. ;; (srfi srfi-1) ; reduce
  23. (contract)
  24. (prefix (lib math) math:)
  25. (lib print-utils))
  26. (let ([a-limit 100] [b-limit 100]
  27. [a-start 2] [b-start 2]
  28. [calc-value (λ (a b) (expt a b))])
  29. (define numbers-table
  30. (let iter ([a a-start]
  31. [b b-start]
  32. [numbers (make-hash-table =)])
  33. (cond
  34. [(> a a-limit)
  35. ;; (print "increase b to" (+ b 1))
  36. (iter a-start (+ b 1) numbers)]
  37. [(> b b-limit)
  38. numbers]
  39. [else
  40. (hash-table-set! numbers (calc-value a b) #t)
  41. (iter (+ a 1) b numbers)])))
  42. ;; (print "numbers:" numbers-table)
  43. (print "distinct values:"
  44. (length
  45. (hash-table-keys numbers-table))))