プロジェクト

全般

プロフィール

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

Noppi, 2024/01/14 08:36

1 1 Noppi
[ホーム](https://redmine.noppi.jp) - [[Wiki|Project Euler]]
2
# [[Problem 35]]
3
4
## Circular Primes
5
The number, $197$, is called a circular prime because all rotations of the digits: $197$, $971$, and $719$, are themselves prime.
6
7
There are thirteen such primes below $100$: $2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79$, and $97$.
8
9
How many circular primes are there below one million?
10
11
## 巡回素数
12
197は巡回素数と呼ばれる. 桁を回転させたときに得られる数 197, 971, 719 が全て素数だからである.
13
14
100未満には巡回素数が13個ある: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, および97である.
15
16
100万未満の巡回素数はいくつあるか?
17
18
```scheme
19 2 Noppi
(import (scheme base)
20
        (gauche base)
21
        (math prime)
22
        (scheme list))
23
24
(define temp-primes (primes))
25
26
(define (number-of-digit n)
27
  (assume (exact-integer? n))
28
  (assume (<= 0 n 99_9999))
29
  (cond
30
    [(<= 0 n 9) 1]
31
    [(<= 10 n 99) 2]
32
    [(<= 100 n 999) 3]
33
    [(<= 1000 n 9999) 4]
34
    [(<= 1_0000 n 9_9999) 5]
35
    [(<= 10_0000 n 99_9999) 6]))
36
;(if (zero? n)
37
;  1
38
;  (+ (floor->exact (fllog10 n))
39
;     1)))
40
41
(define (ml&eml n)
42
  (assume (exact-integer? n))
43
  (assume (<= 0 n))
44
  (let* ([dn (number-of-digit n)]
45
         [module-num (expt 10
46
                           (- dn 1))]
47
         [ml (div n module-num)]
48
         [eml (mod n module-num)])
49
    (values ml eml)))
50
51
(define (circular-digits n)
52
  (assume (exact-integer? n))
53
  (assume (<= 0 n))
54
  (if (< n 10)
55
    `(,n)
56
    (let loop ([num n] [result `(,n)])
57
      (let-values ([(ml-num eml-num) (ml&eml num)])
58
        (if (< eml-num
59
               (expt 10
60
                     (- (number-of-digit n) 2)))
61
          '()
62
          (let ([next (+ (* eml-num 10)
63
                         ml-num)])
64
            (if (find (cut = next <>)
65
                      result)
66
              (reverse result)
67
              (loop next (cons next result)))))))))
68
69
(define (circular-prime? n)
70
  (let ([cd (circular-digits n)])
71
    (and (not (null? cd))
72
         (every prime? cd))))
73
74
(define (prime? n)
75
  (= (car
76
       (drop-while (cut < <> n)
77
                   temp-primes))
78
     n))
79
80
(define (primes-list n)
81
  (take-while (cut <= <> n) temp-primes))
82
83
(define answer-35
84
  (length (filter circular-prime?
85
                  (primes-list 99_9999))))
86
87
(format #t "35: ~d~%" answer-35)
88 1 Noppi
```