Problem 62 » 履歴 » バージョン 2
Noppi, 2024/01/27 15:42
1 | 1 | Noppi | [ホーム](https://redmine.noppi.jp) - [[Wiki|Project Euler]] |
---|---|---|---|
2 | # [[Problem 62]] |
||
3 | |||
4 | ## Cubic Permutations |
||
5 | The cube, $41063625$ ($345^3$), can be permuted to produce two other cubes: $56623104$ ($384^3$) and $66430125$ ($405^3$). In fact, $41063625$ is the smallest cube which has exactly three permutations of its digits which are also cube. |
||
6 | |||
7 | Find the smallest cube for which exactly five permutations of its digits are cube. |
||
8 | |||
9 | ## 立方数置換 |
||
10 | 立方数 $41063625$ ($345^3$) は, 桁の順番を入れ替えると2つの立方数になる: $56623104$ ($384^3$) と $66430125$ ($405^3$) である. $41063625$は, 立方数になるような桁の置換をちょうど3つもつ最小の立方数である. |
||
11 | |||
12 | 立方数になるような桁の置換をちょうど5つもつ最小の立方数を求めよ. |
||
13 | |||
14 | ```scheme |
||
15 | 2 | Noppi | (import (scheme base) |
16 | (gauche base)) |
||
17 | |||
18 | (define (cube num) |
||
19 | (* num num num)) |
||
20 | |||
21 | (define (digit-vector num) |
||
22 | (assume (exact-integer? num)) |
||
23 | (assume (positive? num)) |
||
24 | (let ([result (make-vector 10 0)]) |
||
25 | (let loop ([current num]) |
||
26 | (if (zero? current) |
||
27 | result |
||
28 | (let ([tail-num (mod current 10)]) |
||
29 | (vector-set! result |
||
30 | tail-num |
||
31 | (+ (vector-ref result tail-num) |
||
32 | 1)) |
||
33 | (loop (div current 10))))))) |
||
34 | |||
35 | (define (same-vector? vec1 vec2) |
||
36 | (let loop ([i 0]) |
||
37 | (cond |
||
38 | [(< 9 i) #t] |
||
39 | [(not (= (vector-ref vec1 i) |
||
40 | (vector-ref vec2 i))) |
||
41 | #f] |
||
42 | [else |
||
43 | (loop (+ i 1))]))) |
||
44 | |||
45 | (define (permutate? num1 num2) |
||
46 | (same-vector? (digit-vector num1) |
||
47 | (digit-vector num2))) |
||
48 | |||
49 | (define (permutate-5-number) |
||
50 | ; 345 ~ 464 までが 8 桁の候補 → × |
||
51 | ; 465 ~ 999 までが 9 桁の候補 → × |
||
52 | ; 1002 ~ 2154 までが 10 桁の候補 → × |
||
53 | ; 2155 ~ 4641 までが 11 桁の候補 → × |
||
54 | ; 4642 ~ 9999 までが 12 桁の候補 → ○ |
||
55 | (let loop ([result '()]) |
||
56 | (cond |
||
57 | [(<= 5 (length result)) result] |
||
58 | [(null? result) |
||
59 | (any (^n |
||
60 | (loop (cons n result))) |
||
61 | (iota (- 9999 4642 -1) 4642))] |
||
62 | [else |
||
63 | (let* ([current (car result)] |
||
64 | [next (+ 1 (car result))] |
||
65 | [current-cube (cube current)]) |
||
66 | (if (< 9999 next) |
||
67 | #f |
||
68 | (any (^n |
||
69 | (loop (cons n result))) |
||
70 | (filter (^n |
||
71 | (permutate? current-cube (cube n))) |
||
72 | (iota (- 9999 next -1) next)))))]))) |
||
73 | |||
74 | (define answer-62 |
||
75 | (cube (apply min (permutate-5-number)))) |
||
76 | |||
77 | (format #t "62: ~d~%" answer-62) |
||
78 | 1 | Noppi | ``` |