プロジェクト

全般

プロフィール

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

Noppi, 2024/01/14 09:07

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 3 Noppi
        (scheme list)
23
        (scheme flonum))
24 2 Noppi
25
(define temp-primes (primes))
26
27
(define (number-of-digit n)
28
  (assume (exact-integer? n))
29 3 Noppi
  (assume (<= 0 n))
30
  (if (zero? n)
31
    1
32
    (+ (floor->exact (fllog10 n))
33
       1)))
34 2 Noppi
35
(define (ml&eml n)
36
  (assume (exact-integer? n))
37
  (assume (<= 0 n))
38
  (let* ([dn (number-of-digit n)]
39
         [module-num (expt 10
40
                           (- dn 1))]
41
         [ml (div n module-num)]
42
         [eml (mod n module-num)])
43
    (values ml eml)))
44
45
(define (circular-digits n)
46
  (assume (exact-integer? n))
47 1 Noppi
  (assume (<= 0 n))
48 2 Noppi
  (if (< n 10)
49
    `(,n)
50
    (let loop ([num n] [result `(,n)])
51
      (let-values ([(ml-num eml-num) (ml&eml num)])
52
        (if (< eml-num
53
               (expt 10
54
                     (- (number-of-digit n) 2)))
55
          '()
56
          (let ([next (+ (* eml-num 10)
57
                         ml-num)])
58
            (if (find (cut = next <>)
59
                      result)
60 3 Noppi
              result
61 2 Noppi
              (loop next (cons next result)))))))))
62
63
(define (circular-prime? n)
64
  (let ([cd (circular-digits n)])
65
    (and (not (null? cd))
66
         (every prime? cd))))
67
68
(define (prime? n)
69
  (= (car
70
       (drop-while (cut < <> n)
71
                   temp-primes))
72
     n))
73
74
(define (primes-list n)
75
  (take-while (cut <= <> n) temp-primes))
76
77
(define answer-35
78
  (length (filter circular-prime?
79
                  (primes-list 99_9999))))
80
81
(format #t "35: ~d~%" answer-35)
82 1 Noppi
```