-
Notifications
You must be signed in to change notification settings - Fork 0
/
next_palindrome_in_base.sf
55 lines (43 loc) · 1.61 KB
/
next_palindrome_in_base.sf
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
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/ruby
# A nice algorithm, due to David A. Corneth (Jun 06 2014), for generating the next palindrome from a given palindrome.
# Generalized to other bases by Daniel Suteu (Sep 16 2019).
# See also:
# https://oeis.org/A002113
# https://en.wikipedia.org/wiki/Palindromic_number
func next_palindrome (n, b=10) {
var d = n.digits(b)
var l = d.end
var i = (((d.len+1)>>1) - 1)
while ((i >= 0) && (d[i] == b-1)) {
d[i,l-i] = (0,0)
--i
}
if (i >= 0) {
d[i]++
d[l-i] = d[i]
}
else {
d = (d.len+1).of(0)
d[0,-1] = (1,1)
}
d.digits2num(b)
}
for b in (2 .. 12) {
var a = with (1) { |n|
20.of { n = next_palindrome(n, b) }
}
say a
}
__END__
# Palindromes in bases 2 to 12:
[3, 5, 7, 9, 15, 17, 21, 27, 31, 33, 45, 51, 63, 65, 73, 85, 93, 99, 107, 119]
[2, 4, 8, 10, 13, 16, 20, 23, 26, 28, 40, 52, 56, 68, 80, 82, 91, 100, 112, 121]
[2, 3, 5, 10, 15, 17, 21, 25, 29, 34, 38, 42, 46, 51, 55, 59, 63, 65, 85, 105]
[2, 3, 4, 6, 12, 18, 24, 26, 31, 36, 41, 46, 52, 57, 62, 67, 72, 78, 83, 88]
[2, 3, 4, 5, 7, 14, 21, 28, 35, 37, 43, 49, 55, 61, 67, 74, 80, 86, 92, 98]
[2, 3, 4, 5, 6, 8, 16, 24, 32, 40, 48, 50, 57, 64, 71, 78, 85, 92, 100, 107]
[2, 3, 4, 5, 6, 7, 9, 18, 27, 36, 45, 54, 63, 65, 73, 81, 89, 97, 105, 113]
[2, 3, 4, 5, 6, 7, 8, 10, 20, 30, 40, 50, 60, 70, 80, 82, 91, 100, 109, 118]
[2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 122]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 26, 39, 52, 65, 78, 91, 104, 117, 130]