プロジェクト

全般

プロフィール

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

Noppi, 2024/01/16 12:12

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 2 Noppi
; 10_0000 個目の値は 15049791251 だった
37 1 Noppi
(define pentagonal-num
38
  (let ([table (make-vector 10_0001)])
39 2 Noppi
    (let loop ([i 0] [current 41251] [inc 499])
40 1 Noppi
      (cond
41
        [(< 10_0000 i) table]
42
        [else
43
          (vector-set! table i current)
44
          (loop (+ i 1) (+ current inc) (+ inc 3))]))))
45
46 2 Noppi
; 40755 から次の六角数を 15049791251 を超えないところまで求める
47 1 Noppi
(define hexagonal-num
48
  (list->vector
49 2 Noppi
    (let loop ([current 41328] [inc 577] [lis '()])
50
      (if (< 15049791251 current)
51 1 Noppi
        (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
```