プロジェクト

全般

プロフィール

Problem 45 » 履歴 » バージョン 1

Noppi, 2024/01/16 09:32

1 1 Noppi
[ホーム](https://redmine.noppi.jp) - [[Wiki|Project Euler]]
2
# [[Problem 45]]
3
4
## Triangular, Pentagonal, and Hexagonal
5
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
6
7
|  |  |  |
8
|--|--|--|
9
| Triangle | $T_n=n(n+1)/2$ | $1, 3, 6, 10, 15, \dots$ |
10
| Pentagonal | $P_n=n(3n - 1)/2$ | $1, 5, 12, 22, 35, \dots$ |
11
| Hexagonal | $H_n=n(2n - 1)$ | $1, 6, 15, 28, 45, \dots$ |
12
13
It can be verified that $T_{285} = P_{165} = H_{143} = 40755$.
14
15
Find the next triangle number that is also pentagonal and hexagonal.
16
17
## 三角数, 五角数, 六角数
18
三角数, 五角数, 六角数は以下のように生成される.
19
20
|  |  |  |
21
|--|--|--|
22
| 三角数 | $T_n=n(n+1)/2$ | $1, 3, 6, 10, 15, \dots$ |
23
| 五角数 | $P_n=n(3n - 1)/2$ | $1, 5, 12, 22, 35, \dots$ |
24
| 六角数 | $H_n=n(2n - 1)$ | $1, 6, 15, 28, 45, \dots$ |
25
26
$T_{285} = P_{165} = H_{143} = 40755$ であることが分かる.
27
28
次の三角数かつ五角数かつ六角数な数を求めよ.
29
30
```scheme
31
(import (scheme base)
32
        (gauche base)
33
        (scheme vector))
34
35
; 40755 から次の五角数を 10_0000 個求めてみる
36
; 10_0000 個目の値は 15050091750 だった
37
(define pentagonal-num
38
  (let ([table (make-vector 10_0001)])
39
    (let loop ([i 0] [current 41750] [inc 502])
40
      (cond
41
        [(< 10_0000 i) table]
42
        [else
43
          (vector-set! table i current)
44
          (loop (+ i 1) (+ current inc) (+ inc 3))]))))
45
46
; 40755 から次の六角数を 15050091750 を超えないところまで求める
47
(define hexagonal-num
48
  (list->vector
49
    (let loop ([current 40755] [inc 573] [lis '()])
50
      (if (< 15050091750 current)
51
        (reverse lis)
52
        (loop (+ current inc) (+ inc 4) (cons current lis))))))
53
54
(define (pentagonal-num? num)
55
  (vector-binary-search
56
    pentagonal-num
57
    num
58
    (^[a b] (- a b))))
59
60
(define find-tph
61
  (let ([count (vector-length hexagonal-num)])
62
    (let loop ([i 0])
63
      (if (<= count i)
64
        (errorf "解が見つかりませんでした~%")
65
        (let ([current (vector-ref hexagonal-num i)])
66
          (if (pentagonal-num? current)
67
            current
68
            (loop (+ i 1))))))))
69
70
(define answer-45 find-tph)
71
72
(format #t "45: ~d~%" answer-45)
73
```