125.scm 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. ;; Palindromic sums
  2. (define module (test test))
  3. (use-modules (euler utils)
  4. (srfi srfi-1)
  5. (rnrs sorting))
  6. (define (get-consecutive-square-sums n)
  7. (define squares (get-squares n))
  8. (define (init-square-sum i)
  9. (+ (array-ref squares i)
  10. (array-ref squares (1+ i))))
  11. ;; TODO: make current sum the thing to check..
  12. ;; ASSUMING we have an array with more than one item
  13. (let generator ((i 0) (j 1) (curr-sum (init-square-sum 0)) (acc '()))
  14. (cond
  15. ((>= i (- (array-length squares) 2)) acc)
  16. ((>= curr-sum n) (generator (1+ i) (+ 2 i) (init-square-sum (1+ i)) acc))
  17. ((>= j (array-length squares)) (generator (1+ i) (+ 2 i) (init-square-sum (1+ i)) acc))
  18. (else (generator i (1+ j)
  19. (+ curr-sum (array-ref squares (1+ j)))
  20. (cons curr-sum acc))))))
  21. (define (get-squares n)
  22. (let generator ((i 1) (acc '()))
  23. (let ((square (expt i 2)))
  24. (if (>= square n) (list->array 1 (reverse acc))
  25. (generator (1+ i) (cons square acc))))))
  26. (define (quick-delete-duplicates lst)
  27. (let loop ((sorted-lst (list-sort < lst)) (unique-lst '()))
  28. (cond
  29. ((= 1 (length sorted-lst)) (cons (car sorted-lst) unique-lst))
  30. ((= (car sorted-lst) (cadr sorted-lst))
  31. (loop (cdr sorted-lst) unique-lst))
  32. (else (loop (cdr sorted-lst) (cons (car sorted-lst) unique-lst))))))
  33. (define-public (digit-length n)
  34. (string-length (number->string n)))
  35. (display
  36. (fold + 0
  37. (filter (lambda (n)
  38. (palendromic? (number->string n)))
  39. (delete-duplicates (get-consecutive-square-sums (expt 10 8))))))
  40. (newline)