Last active
February 25, 2024 11:08
-
-
Save neteroster/9f59b6a868ef26fc7a43ce6a3eaac4bd to your computer and use it in GitHub Desktop.
从 [1, 100] 中选择 10 个不同的整数,使得它们的倒数和为 1,计算所有的选择方法。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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