004.scm 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. ;; https://projecteuler.net/problem=4
  2. ;; Largest palindrome product
  3. ;; Problem 4
  4. ;; A palindromic number reads the same both ways. The
  5. ;; largest palindrome made from the product of two 2-digit
  6. ;; numbers is 9009 = 91 × 99.
  7. ;; Find the largest palindrome made from the product of two
  8. ;; 3-digit numbers.
  9. (import
  10. (except (rnrs base) let-values)
  11. (only (guile)
  12. ;; lambda forms
  13. lambda* λ
  14. sqrt)
  15. (srfi srfi-1))
  16. (define palindrome-number?
  17. (λ (num)
  18. (let ([num-as-str (number->string num)])
  19. (string=? (reverse-list->string (string->list num-as-str))
  20. num-as-str))))
  21. (define find-palindrome-products
  22. (λ ()
  23. (let next ([fac-outer 100] [fac-inner 100] [found-max-palimdrome '0])
  24. (cond
  25. [(> fac-outer 999)
  26. found-max-palimdrome]
  27. [(> fac-inner 999)
  28. (next (+ fac-outer 1) 100 found-max-palimdrome)]
  29. [else
  30. (let ([product (* fac-outer fac-inner)])
  31. (cond
  32. [(palindrome-number? product)
  33. (simple-format (current-output-port)
  34. "~a x ~a = ~a\n"
  35. fac-outer
  36. fac-inner
  37. product)
  38. (next fac-outer
  39. (+ fac-inner 1)
  40. (max found-max-palimdrome product))]
  41. [else
  42. (next fac-outer
  43. (+ fac-inner 1)
  44. found-max-palimdrome)]))]))))
  45. (simple-format
  46. (current-output-port)
  47. "~a\n"
  48. (find-palindrome-products))