Problem 36 » 履歴 » バージョン 2
Noppi, 2024/01/14 12:18
1 | 1 | Noppi | [ホーム](https://redmine.noppi.jp) - [[Wiki|Project Euler]] |
---|---|---|---|
2 | # [[Problem 36]] |
||
3 | |||
4 | ## Double-base Palindromes |
||
5 | The decimal number, $585 = 1001001001_2$ (binary), is palindromic in both bases. |
||
6 | |||
7 | Find the sum of all numbers, less than one million, which are palindromic in base $10$ and base $2$. |
||
8 | |||
9 | (Please note that the palindromic number, in either base, may not include leading zeros.) |
||
10 | |||
11 | ## 二種類の基数による回文数 |
||
12 | $585 = 1001001001_2$ (2進) は10進でも2進でも回文数である. |
||
13 | |||
14 | 100万未満で10進でも2進でも回文数になるような数の総和を求めよ. |
||
15 | |||
16 | (注: 先頭に0を含めて回文にすることは許されない.) |
||
17 | |||
18 | ```scheme |
||
19 | 2 | Noppi | (import (scheme base) |
20 | (gauche base) |
||
21 | (scheme flonum)) |
||
22 | |||
23 | (define (number-of-digit n base) |
||
24 | (assume (exact-integer? n)) |
||
25 | (assume (<= 0 n)) |
||
26 | (assume (or (= base 2) |
||
27 | (= base 10))) |
||
28 | (if (zero? n) |
||
29 | 1 |
||
30 | (+ (floor->exact |
||
31 | ((if (= base 2) |
||
32 | fllog2 |
||
33 | fllog10) |
||
34 | n)) |
||
35 | 1))) |
||
36 | |||
37 | (define (palindrome? n base) |
||
38 | (assume (exact-integer? n)) |
||
39 | (assume (<= 0 n)) |
||
40 | (assume (or (= base 2) |
||
41 | (= base 10))) |
||
42 | (let* ([dn (number-of-digit n base)] |
||
43 | [loop-count (div dn 2)]) |
||
44 | (let loop ([index 0]) |
||
45 | (cond |
||
46 | [(<= loop-count index) #t] |
||
47 | [(= (div (mod n (expt base (+ 1 index))) |
||
48 | (expt base index)) |
||
49 | (div (mod n (expt base (- dn index))) |
||
50 | (expt base (- dn 1 index)))) |
||
51 | (loop (+ index 1))] |
||
52 | [else #f])))) |
||
53 | |||
54 | (define answer-36 |
||
55 | (apply + |
||
56 | (filter (cut palindrome? <> 2) |
||
57 | (filter (cut palindrome? <> 10) |
||
58 | (iota 100_0000))))) |
||
59 | |||
60 | (format #t "36: ~d~%" answer-36) |
||
61 | 1 | Noppi | ``` |