Skip to content

Instantly share code, notes, and snippets.

@neteroster
Last active February 25, 2024 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neteroster/9f59b6a868ef26fc7a43ce6a3eaac4bd to your computer and use it in GitHub Desktop.
Save neteroster/9f59b6a868ef26fc7a43ce6a3eaac4bd to your computer and use it in GitHub Desktop.
从 [1, 100] 中选择 10 个不同的整数,使得它们的倒数和为 1,计算所有的选择方法。
#lang racket/base
(define res-port (open-output-file "resf.txt"))
(display "make table: ")
(define sum-table
(time
(for*/fold ([h (make-hash)])
([i (in-range 1 101)]
[j (in-range (+ i 1) 101)]
[k (in-range (+ j 1) 101)])
(hash-update! h
(+ (/ 1 i) (/ 1 j) (/ 1 k))
(λ (x) (cons (list k j i) x))
'())
h)))
(define (backtrack path start target n)
(cond
[(= n 3)
(when (hash-has-key? sum-table target)
(for ([c (in-list (hash-ref sum-table target))]
#:when (>= (caddr c) start))
(displayln (append c path) res-port)))]
[else
(let* ((kmax (floor (/ n target)))
(end (+ 1 (min 100 kmax))))
(for ([i (in-range start end)]
#:when (< (/ 1 i) target))
(backtrack (cons i path)
(+ i 1)
(- target (/ 1 i))
(- n 1))))]))
(display "backtrack: ")
(time (backtrack '() 1 1 10))
(close-output-port res-port)
;; My laptop: AMD Ryzen 5800U
;; make table: cpu time: 140 real time: 145 gc time: 31
;; backtrack: cpu time: 8140 real time: 8131 gc time: 46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment