-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path037 Truncatable primes.sf
More file actions
45 lines (31 loc) · 1.08 KB
/
037 Truncatable primes.sf
File metadata and controls
45 lines (31 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/ruby
# Daniel "Trizen" Șuteu
# Edit: 04 February 2019
# Edit: 28 March 2023
# https://github.com/trizen
# Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
# NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
# https://projecteuler.net/problem=37
# Runtime: 0.265s
func is_left_truncatable_prime(digits, base) {
^digits -> all {|k| digits.first(k+1).digits2num(base).is_prime }
}
func generate_from_prefix(p, base) {
var seq = [p]
for n in (1 ..^ base) {
var t = [n, p...]
if (t.digits2num(base).is_prime) {
seq << __FUNC__(t, base).grep { is_left_truncatable_prime(_, base) }...
}
}
return seq
}
func both_truncatable_primes(base) { # finite sequence for each base
var prime_digits = (base-1 -> primes) # prime digits < base
prime_digits.map {|p| generate_from_prefix([p], base)... }\
.map {|t| digits2num(t, base) }\
.sort
}
var base = 10
var T = both_truncatable_primes(base)
say T.grep { _ >= base }.sum