I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

Numbers in base 10 that are palindromic in bases 2, 4, and 16

From Rosetta Code
Numbers in base 10 that are palindromic in bases 2, 4, and 16 is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Task
Find numbers in base 10 that are palindromic in bases 2, 4, and 16, where n < 25,000



ALGOL 68[edit]

BEGIN # show numbers in decimal that are palindromic in bases 2, 4 and 16 #
INT max number = 25 000; # maximum number to consider #
INT min base = 2; # smallest base needed #
INT max digits = BEGIN # number of digits max number has in the smallest base #
INT d := 1;
INT v := max number;
WHILE v >= min base DO
v OVERAB min base;
d PLUSAB 1
OD;
d
END;
# returns the digits of n in the specified base #
PRIO DIGITS = 9;
OP DIGITS = ( INT n, INT base )[]INT:
IF INT v := ABS n;
v < base
THEN v # single dogit #
ELSE # multiple digits #
[ 1 : max digits ]INT result;
INT d pos := UPB result + 1;
INT v := ABS n;
WHILE v > 0 DO
result[ d pos -:= 1 ] := v MOD base;
v OVERAB base
OD;
result[ d pos : UPB result ]
FI # DIGITS # ;
# returns TRUE if the digits in d form a palindrome, FALSE otherwise #
OP PALINDROMIC = ( []INT d )BOOL:
BEGIN
INT left := LWB d, right := UPB d;
BOOL is palindromic := TRUE;
WHILE left < right AND is palindromic DO
is palindromic := d[ left ] = d[ right ];
left +:= 1;
right -:= 1
OD;
is palindromic
END;
# print the numbers in decimal that are palendromic in bases 2, 4 and 16 #
FOR n FROM 0 TO max number DO
IF PALINDROMIC ( n DIGITS 16 ) THEN
IF PALINDROMIC ( n DIGITS 4 ) THEN
IF PALINDROMIC ( n DIGITS 2 ) THEN
print( ( " ", whole( n, 0 ) ) )
FI
FI
FI
OD
END
Output:
 0 1 3 5 15 17 51 85 255 257 273 771 819 1285 1365 3855 4095 4097 4369 12291 13107 20485 21845

APL[edit]

Works with: Dyalog APL
(⊢(/⍨)(2 4 16∧.((⊢≡⌽)(⊥⍣¯1))⊢)¨)0,⍳24999
Output:
0 1 3 5 15 17 51 85 255 257 273 771 819 1285 1365 3855 4095 4097 4369 12291 13107 20485 21845

AWK[edit]

 
# syntax: GAWK -f NUMBERS_IN_BASE_10_THAT_ARE_PALINDROMIC_IN_BASES_2_4_AND_16.AWK
# converted from C
BEGIN {
start = 0
stop = 24999
for (i=start; i<stop; i++) {
if (palindrome(i,2) && palindrome(i,4) && palindrome(i,16)) {
printf("%5d%1s",i,++count%10?"":"\n")
}
}
printf("\nBase 10 numbers that are palindromes in bases 2, 4, and 16: %d-%d: %d\n",start,stop,count)
exit(0)
}
function palindrome(n,base) {
return n == reverse(n,base)
}
function reverse(n,base, r) {
for (r=0; n; n=int(n/base)) {
r = int(r*base) + n%base
}
return(r)
}
 
Output:
    0     1     3     5    15    17    51    85   255   257
  273   771   819  1285  1365  3855  4095  4097  4369 12291
13107 20485 21845
Base 10 numbers that are palindromes in bases 2, 4, and 16: 0-24999: 23

BASIC[edit]

10 DEFINT A-Z: DEFDBL R
20 FOR I=1 TO 25000
30 B=2: GOSUB 100: IF R<>I GOTO 70
40 B=4: GOSUB 100: IF R<>I GOTO 70
50 B=16: GOSUB 100: IF R<>I GOTO 70
60 PRINT I,
70 NEXT
80 END
100 R=0: N=I
110 IF N=0 THEN RETURN
120 R=R*B+N MOD B
130 N=N\B
140 GOTO 110
Output:
 0             1             3             5             15
 17            51            85            255           257
 273           771           819           1285          1365
 3855          4095          4097          4369          12291
 13107         20485         21845

BCPL[edit]

get "libhdr"
manifest $( MAXIMUM = 25000 $)
 
let reverse(n, base) = valof
$( let r = 0
while n > 0
$( r := r*base + n rem base
n := n / base
$)
resultis r
$)
 
let palindrome(n, base) = n = reverse(n, base)
 
let start() be
for i = 0 to MAXIMUM
if palindrome(i,2) & palindrome(i,4) & palindrome(i,16)
do writef("%N*N", i)
Output:
0
1
3
5
15
17
51
85
255
257
273
771
819
1285
1365
3855
4095
4097
4369
12291
13107
20485
21845

C[edit]

#include <stdio.h>
#define MAXIMUM 25000
 
int reverse(int n, int base) {
int r;
for (r = 0; n; n /= base)
r = r*base + n%base;
return r;
}
 
int palindrome(int n, int base) {
return n == reverse(n, base);
}
 
int main() {
int i, c = 0;
 
for (i = 0; i < MAXIMUM; i++) {
if (palindrome(i, 2) &&
palindrome(i, 4) &&
palindrome(i, 16)) {
printf("%5d%c", i, ++c % 12 ? ' ' : '\n');
}
}
printf("\n");
return 0;
}
Output:
    0     1     3     5    15    17    51    85   255   257   273   771
  819  1285  1365  3855  4095  4097  4369 12291 13107 20485 21845

COBOL[edit]

       IDENTIFICATION DIVISION.
PROGRAM-ID. PALINDROMIC-BASE-2-4-16.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 VARIABLES.
02 CUR-NUM PIC 9(5).
02 REV-BASE PIC 99.
02 REV-REST PIC 9(5).
02 REV-NEXT PIC 9(5).
02 REV-DGT PIC 99.
02 REVERSED PIC 9(5).
 
01 OUTPUT-FORMAT.
02 OUT-NUM PIC Z(4)9.
 
PROCEDURE DIVISION.
BEGIN.
PERFORM 2-4-16-PALINDROME
VARYING CUR-NUM FROM ZERO BY 1
UNTIL CUR-NUM IS NOT LESS THAN 25000.
STOP RUN.
 
2-4-16-PALINDROME.
MOVE 16 TO REV-BASE, PERFORM REVERSE THRU REV-LOOP
IF CUR-NUM IS EQUAL TO REVERSED
MOVE 4 TO REV-BASE, PERFORM REVERSE THRU REV-LOOP
IF CUR-NUM IS EQUAL TO REVERSED
MOVE 2 TO REV-BASE, PERFORM REVERSE THRU REV-LOOP
IF CUR-NUM IS EQUAL TO REVERSED
MOVE CUR-NUM TO OUT-NUM
DISPLAY OUT-NUM.
 
REVERSE.
MOVE ZERO TO REVERSED.
MOVE CUR-NUM TO REV-REST.
REV-LOOP.
IF REV-REST IS GREATER THAN ZERO
DIVIDE REV-BASE INTO REV-REST GIVING REV-NEXT
COMPUTE REV-DGT = REV-REST - REV-NEXT * REV-BASE
MULTIPLY REV-BASE BY REVERSED
ADD REV-DGT TO REVERSED
MOVE REV-NEXT TO REV-REST
GO TO REV-LOOP.
Output:
    0
    1
    3
    5
   15
   17
   51
   85
  255
  257
  273
  771
  819
 1285
 1365
 3855
 4095
 4097
 4369
12291
13107
20485
21845

Cowgol[edit]

include "cowgol.coh";
const MAXIMUM := 25000;
 
sub reverse(n: uint16, base: uint16): (r: uint16) is
r := 0;
while n != 0 loop
r := r * base + n % base;
n := n / base;
end loop;
end sub;
 
var i: uint16 := 0;
var c: uint8 := 0;
while i < MAXIMUM loop
if reverse(i,2) == i
and reverse(i,4) == i
and reverse(i,16) == i
then
c := c + 1;
print_i16(i);
if c == 15 then
print_nl();
c := 0;
else
print_char(' ');
end if;
end if;
i := i + 1;
end loop;
print_nl();
Output:
0 1 3 5 15 17 51 85 255 257 273 771 819 1285 1365
3855 4095 4097 4369 12291 13107 20485 21845

F#[edit]

 
// Palindromic numbers in bases 2,4, and 16. Nigel Galloway: June 25th., 2021
let fG n g=let rec fG n g=[yield n%g; if n>=g then yield! fG(n/g) g] in let n=fG n g in n=List.rev n
Seq.initInfinite id|>Seq.takeWhile((>)25000)|>Seq.filter(fun g->fG g 16 && fG g 4 && fG g 2)|>Seq.iter(printf "%d "); printfn ""
 
Output:
0 1 3 5 15 17 51 85 255 257 273 771 819 1285 1365 3855 4095 4097 4369 12291 13107 20485 21845

Factor[edit]

Works with: Factor version 0.99 2021-06-02
USING: io kernel math.parser prettyprint sequences ;
 
25,000 <iota> [
{ 2 4 16 } [ >base ] with map [ dup reverse = ] all?
] filter [ pprint bl ] each nl
Output:
0 1 3 5 15 17 51 85 255 257 273 771 819 1285 1365 3855 4095 4097 4369 12291 13107 20485 21845 

Go[edit]

Library: Go-rcu
package main
 
import (
"fmt"
"rcu"
"strconv"
)
 
func reverse(s string) string {
chars := []rune(s)
for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
chars[i], chars[j] = chars[j], chars[i]
}
return string(chars)
}
 
func main() {
fmt.Println("Numbers under 25,000 in base 10 which are palindromic in bases 2, 4 and 16:")
var numbers []int
for i := int64(0); i < 25000; i++ {
b2 := strconv.FormatInt(i, 2)
if b2 == reverse(b2) {
b4 := strconv.FormatInt(i, 4)
if b4 == reverse(b4) {
b16 := strconv.FormatInt(i, 16)
if b16 == reverse(b16) {
numbers = append(numbers, int(i))
}
}
}
}
for i, n := range numbers {
fmt.Printf("%6s ", rcu.Commatize(n))
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\n\nFound", len(numbers), "such numbers.")
}
Output:
Numbers under 25,000 in base 10 which are palindromic in bases 2, 4 and 16:
     0      1      3      5     15     17     51     85    255    257 
   273    771    819  1,285  1,365  3,855  4,095  4,097  4,369 12,291 
13,107 20,485 21,845 

Found 23 such numbers.

Julia[edit]

palinbases(n, bases = [2, 4, 16]) = all(b -> (d = digits(n, base = b); d == reverse(d)), bases)
 
foreach(p -> print(rpad(p[2], 7), p[1] % 11 == 0 ? "\n" : ""), enumerate(filter(palinbases, 1:25000)))
 
Output:
1      3      5      15     17     51     85     255    257    273    771    
819    1285   1365   3855   4095   4097   4369   12291  13107  20485  21845

Nim[edit]

import strutils, sugar
 
type Digit = 0..15
 
func toBase(n: Natural; b: Positive): seq[Digit] =
if n == 0: return @[Digit 0]
var n = n
while n != 0:
result.add n mod b
n = n div b
 
func isPalindromic(s: seq[Digit]): bool =
for i in 1..(s.len div 2):
if s[i-1] != s[^i]: return false
result = true
 
let list = collect(newSeq):
for n in 0..<25_000:
if n.toBase(2).isPalindromic and
n.toBase(4).isPalindromic and
n.toBase(16).isPalindromic: n
 
echo "Found ", list.len, " numbers which are palindromic in bases 2, 4 and 16:"
echo list.join(" ")
Output:
Found 23 numbers which are palindromic in bases 2, 4 and 16:
0 1 3 5 15 17 51 85 255 257 273 771 819 1285 1365 3855 4095 4097 4369 12291 13107 20485 21845

Perl[edit]

Library: ntheory
use strict;
use warnings;
use ntheory 'todigitstring';
 
sub pb { my $s = todigitstring(shift,shift); return $s eq join '', reverse split '', $s }
 
pb($_,2) and pb($_,4) and pb($_,16) and print "$_ " for 1..25000;
Output:
1 3 5 15 17 51 85 255 257 273 771 819 1285 1365 3855 4095 4097 4369 12291 13107 20485 21845

Phix[edit]

with javascript_semantics
function palindrome(string s) return s=reverse(s) end function
function p2416(integer n)
    return palindrome(sprintf("%a",{{2,n}}))
       and palindrome(sprintf("%a",{{4,n}}))
       and palindrome(sprintf("%a",{{16,n}}))
end function
sequence res = apply(filter(tagset(25000,0),p2416),sprint)
printf(1,"%d found: %s\n",{length(res),join(res)})
Output:
23 found: 0 1 3 5 15 17 51 85 255 257 273 771 819 1285 1365 3855 4095 4097 4369 12291 13107 20485 21845

PL/M[edit]

100H:
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
 
DECLARE MAXIMUM LITERALLY '25$000';
 
/* PRINT A NUMBER */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (7) BYTE INITIAL ('..... $');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = N MOD 10 + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;
 
/* REVERSE NUMBER GIVEN BASE */
REVERSE: PROCEDURE (N, B) ADDRESS;
DECLARE (N, R) ADDRESS, B BYTE;
R = 0;
DO WHILE N > 0;
R = R*B + N MOD B;
N = N/B;
END;
RETURN R;
END REVERSE;
 
/* CHECK IF NUMBER IS PALINDROME */
PALIN: PROCEDURE (N, B) BYTE;
DECLARE N ADDRESS, B BYTE;
RETURN N = REVERSE(N, B);
END PALIN;
 
DECLARE I ADDRESS, C BYTE;
C = 0;
DO I = 0 TO MAXIMUM;
IF PALIN(I,2) AND PALIN(I,4) AND PALIN(I,16) THEN DO;
CALL PRINT$NUMBER(I);
C = C + 1;
IF C = 15 THEN DO;
CALL PRINT(.(13,10,'$'));
C = 0;
END;
END;
END;
CALL EXIT;
EOF
Output:
0 1 3 5 15 17 51 85 255 257 273 771 819 1285 1365
3855 4095 4097 4369 12291 13107 20485 21845

Python[edit]

def reverse(n, base):
r = 0
while n > 0:
r = r*base + n%base
n = n//base
return r
 
def palindrome(n, base):
return n == reverse(n, base)
 
cnt = 0
for i in range(25000):
if all(palindrome(i, base) for base in (2,4,16)):
cnt += 1
print("{:5}".format(i), end=" \n"[cnt % 12 == 0])
 
print()
Output:
    0     1     3     5    15    17    51    85   255   257   273   771
  819  1285  1365  3855  4095  4097  4369 12291 13107 20485 21845

Raku[edit]

put "{+$_} such numbers:\n", .batch(10)».fmt('%5d').join("\n") given
(^25000).grep: -> $n { all (2,4,16).map: { $n.base($_) eq $n.base($_).flip } }
Output:
23 such numbers:
    0     1     3     5    15    17    51    85   255   257
  273   771   819  1285  1365  3855  4095  4097  4369 12291
13107 20485 21845

REXX[edit]

Programming note:   the conversions of a decimal number to another base (radix) was ordered such that the fastest
base conversion was performed before the other conversions.

The use of REXX's BIFs to convert decimal numbers to binary and hexadecimal were used   (instead of the   base  
function)   because they are much faster).

This REXX version takes advantage that no   even   integers need be tested   (except for the single exception:   zero),
this makes the execution twice as fast.

/*REXX pgm finds non─neg integers that are palindromes in base 2, 4, and 16, where N<25k*/
numeric digits 100 /*ensure enough dec. digs for large #'s*/
parse arg n cols . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n = 25000 /*Not specified? Then use the default.*/
if cols=='' | cols=="," then cols= 10 /* " " " " " " */
w= 10 /*width of a number in any column. */
title= ' non-negative integers that are palindromes in base 2, 4, and 16, where N < ' ,
commas(n)
say ' index │'center(title, 1 + cols*(w+1) ) /*display the title for the output. */
say '───────┼'center("" , 1 + cols*(w+1), '─') /* " a sep " " " */
$= right(0, w+1) /*list of numbers found (so far). */
found= 1 /*# of finds (so far), the only even #.*/
idx= 1 /*set the IDX (index) to unity. */
do j=1 by 2 to n-1 /*find int palindromes in bases 2,4,16.*/
h= d2x(j) /*convert dec. # to hexadecimal. */
if h\==reverse(h) then iterate /*Hex number not palindromic? Skip.*/ /* ◄■■■■■■■■ a filter. */
b= x2b( d2x(j) ) + 0 /*convert dec. # to hex, then to binary*/
if b\==reverse(b) then iterate /*Binary number not palindromic? Skip.*/ /* ◄■■■■■■■■ a filter. */
q= base(j, 4) /*convert a decimal integer to base 4. */
if q\==reverse(q) then iterate /*Base 4 number not palindromic? Skip.*/ /* ◄■■■■■■■■ a filter. */
found= found + 1 /*bump number of found such numbers. */
$= $ right( commas(j), w) /*add the found number ───► $ list. */
if found // cols \== 0 then iterate /*have we populated a line of output? */
say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */
idx= idx + cols /*bump the index count for the output*/
end /*j*/
 
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/
say '───────┴'center("" , 1 + cols*(w+1), '─') /*display the foot sep for output. */
say
say 'Found ' found title
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
base: procedure; parse arg #,t,,y; @= 0123456789abcdefghijklmnopqrstuvwxyz /*up to 36*/
@@= substr(@, 2); do while #>=t; y= substr(@, #//t + 1, 1)y; #= # % t
end; return substr(@, #+1, 1)y
output   when using the default inputs:
 index │             non-negative integers that are palindromes in base 2, 4, and 16,  where  N  <  25,000
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────
   1   │          0          1          3          5         15         17         51         85        255        257
  11   │        273        771        819      1,285      1,365      3,855      4,095      4,097      4,369     12,291
  21   │     13,107     20,485     21,845
───────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────

Found  23  non-negative integers that are palindromes in base 2, 4, and 16,  where  N  <  25,000

Ring[edit]

 
load "stdlib.ring"
see "working..." + nl
see "Numbers in base 10 that are palindromic in bases 2, 4, and 16:" + nl
 
row = 0
limit = 25000
 
for n = 1 to limit
base2 = decimaltobase(n,2)
base4 = decimaltobase(n,4)
base16 = hex(n)
bool = ispalindrome(base2) and ispalindrome(base4) and ispalindrome(base16)
if bool = 1
see "" + n + " "
row = row + 1
if row%5 = 0
see nl
ok
ok
next
 
see nl + "Found " + row + " numbers" + nl
see "done..." + nl
 
func decimaltobase(nr,base)
decList = 0:15
baseList = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
 
binList = []
binary = 0
remainder = 1
while(nr != 0)
remainder = nr % base
ind = find(decList,remainder)
rem = baseList[ind]
add(binList,rem)
nr = floor(nr/base)
end
binlist = reverse(binList)
binList = list2str(binList)
binList = substr(binList,nl,"")
return binList
 
Output:
working...
Numbers in base 10 that are palindromic in bases 2, 4, and 16:
1 3 5 15 17 
51 85 255 257 273 
771 819 1285 1365 3855 
4095 4097 4369 12291 13107 
20485 21845 
Found 22 numbers
done...

Seed7[edit]

$ include "seed7_05.s7i";
 
const func boolean: palindrome (in string: input) is
return input = reverse(input);
 
const proc: main is func
local
var integer: n is 1;
begin
write("0 ");
for n range 1 to 24999 step 2 do
if palindrome(n radix 2) and palindrome(n radix 4) and palindrome(n radix 16) then
write(n <& " ");
end if;
end for;
end func;
Output:
0 1 3 5 15 17 51 85 255 257 273 771 819 1285 1365 3855 4095 4097 4369 12291 13107 20485 21845

Sidef[edit]

say gather {
for (var k = 0; k < 25_000; k = k.next_palindrome(16)) {
take(k) if [2, 4].all{|b| k.is_palindrome(b) }
}
}
Output:
[0, 1, 3, 5, 15, 17, 51, 85, 255, 257, 273, 771, 819, 1285, 1365, 3855, 4095, 4097, 4369, 12291, 13107, 20485, 21845]

Wren[edit]

Library: Wren-fmt
Library: Wren-seq
import "/fmt" for Conv, Fmt
import "/seq" for Lst
 
System.print("Numbers under 25,000 in base 10 which are palindromic in bases 2, 4 and 16:")
var numbers = []
for (i in 0..24999) {
var b2 = Conv.itoa(i, 2)
if (b2 == b2[-1..0]) {
var b4 = Conv.itoa(i, 4)
if (b4 == b4[-1..0]) {
var b16 = Conv.itoa(i, 16)
if (b16 == b16[-1..0]) numbers.add(i)
}
}
}
for (chunk in Lst.chunks(numbers, 8)) Fmt.print("$,6d", chunk)
System.print("\nFound %(numbers.count) such numbers.")
Output:
Numbers under 25,000 in base 10 which are palindromic in bases 2, 4 and 16:
     0      1      3      5     15     17     51     85
   255    257    273    771    819  1,285  1,365  3,855
 4,095  4,097  4,369 12,291 13,107 20,485 21,845

Found 23 such numbers.

XPL0[edit]

func Reverse(N, Base);  \Reverse order of digits in N for given Base
int N, Base, M;
[M:= 0;
repeat N:= N/Base;
M:= M*Base + rem(0);
until N=0;
return M;
];
 
int Count, N;
[Count:= 0;
for N:= 1 to 25000-1 do
if N = Reverse(N, 2) &
N = Reverse(N, 4) &
N = Reverse(N, 16) then
[IntOut(0, N);
Count:= Count+1;
if rem(Count/10) = 0 then CrLf(0) else ChOut(0, 9\tab\);
];
CrLf(0);
IntOut(0, Count);
Text(0, " such numbers found.
");
]
Output:
1       3       5       15      17      51      85      255     257     273
771     819     1285    1365    3855    4095    4097    4369    12291   13107
20485   21845   
22 such numbers found.