29
\$\begingroup\$

Given a positive integer N, output the smallest positive integer such that this number is a palindrome (i.e. is its own reverse) and is divisible by N.

The palindrome (i.e. the output) must not need a leading zero to be a palindrome, e.g. 080 is not the valid answer for 16.

The input will never be a multiple of 10, because of the previous reason.

Your program may take as much time as necessary, even if in practice it would be way too long to output the answer.

Inputs and outputs

  • You may take the input through STDIN, as a function argument, or anything similar.
  • You may print the output to STDOUT, return it from a function, or anything similar.
  • Inputs and outputs must be in the decimal base.

Test cases

N Output
1 1
2 2
16 272
17 272
42 252
111 111
302 87278
1234 28382

Scoring

This is , so the shortest answer in bytes wins.

asked Aug 25, 2016 at 6:41
\$\endgroup\$
11
  • \$\begingroup\$ Will the input be divisible by 10? \$\endgroup\$ Commented Aug 25, 2016 at 7:01
  • \$\begingroup\$ @LeakyNun No, because then there is no solution since the palindrome must not need a leading zero. I will make that explicit. \$\endgroup\$ Commented Aug 25, 2016 at 7:04
  • \$\begingroup\$ Will the input be positive? \$\endgroup\$ Commented Aug 25, 2016 at 14:01
  • 1
    \$\begingroup\$ @WheatWizard Yes: Given a positive integer N \$\endgroup\$ Commented Aug 25, 2016 at 14:29
  • 1
    \$\begingroup\$ This is related to sequence A062279. @Adamátor, Mathematics demonstrates that there is a finite multiplier for any input. The multipliers are quite chaotic! \$\endgroup\$ Commented Nov 5 at 14:13

48 Answers 48

1
2
15
\$\begingroup\$

Haskell, (削除) 45 (削除ここまで) (削除) 37 (削除ここまで) 34 bytes

(+)>>=until((reverse>>=(==)).show)
answered Aug 25, 2016 at 11:11
\$\endgroup\$
13
\$\begingroup\$

Pyth, 7 bytes

*f_I`*Q

Try it online: Demonstration

Explanation

*f_I`*QT)Q implicit endings, Q=input number
 f ) find the first number T >= 1, which satisfies:
 *QT product of Q and T
 ` as string
 _I is invariant under inversion (=palindrom)
* Q multiply this number with Q and print
answered Aug 25, 2016 at 6:49
\$\endgroup\$
2
  • \$\begingroup\$ After reading so many codegold questions I'm starting to think that Pyth will be next JS/Java/Ruby/Python... \$\endgroup\$ Commented Aug 25, 2016 at 12:00
  • 6
    \$\begingroup\$ @agilob oh dear god pls no. \$\endgroup\$ Commented Aug 26, 2016 at 20:14
9
\$\begingroup\$

2sable / 05AB1E, 6 / 7 bytes

2sable

[DÂQ#+

Explanation

[ # infinite loop
 D # duplicate current number
 Â # bifurcate
 Q# # if the number is equal to its reverse, break loop
 + # add input
 # implicitly print

Try it online

05AB1E

[DÂQ#1+

The difference to the 2sable code is that input is only implicit once in 05AB1E, so here we need 1 to get the first input again.

Try it online

Saved 1 byte with 2sable as suggested by Adnan

answered Aug 25, 2016 at 6:55
\$\endgroup\$
3
  • \$\begingroup\$ @Fatalize I was just writing it up :) \$\endgroup\$ Commented Aug 25, 2016 at 6:57
  • \$\begingroup\$ If you switch to 2sable, you can save a byte by doing this: [DÂQ#+. \$\endgroup\$ Commented Aug 25, 2016 at 8:42
  • \$\begingroup\$ @Adnan: Right! The repeated implicit input saves a byte :) \$\endgroup\$ Commented Aug 25, 2016 at 8:46
7
\$\begingroup\$

Java, (削除) 164 (削除ここまで) (削除) 159 (削除ここまで) (削除) 126 (削除ここまで) (削除) 108 (削除ここまで) 94 bytes

Golfed version:

int c(int a){int x=a;while(!(x+"").equals(new StringBuffer(x+"").reverse()+""))x+=a;return x;}

Ungolfed version:

int c(int a)
{
 int x = a;
 while (!(x + "").equals(new StringBuffer(x + "").reverse() + ""))
 x += a;
 return x;
}

Shoutout to Emigna and Kevin Cruijssen for contributing improvements and cutting the bytes almost in half :)

answered Aug 25, 2016 at 9:07
\$\endgroup\$
11
  • 1
    \$\begingroup\$ Isn't x % a == 0 kind of redundant when you initialize x as a and only increase it by a? Also, can the comparison with the reversal of the string be done in the while conditional? \$\endgroup\$ Commented Aug 25, 2016 at 9:12
  • \$\begingroup\$ You can remove import org.apache.commons.lang.StringUtils; and use org.apache.commons.lang.StringUtils.reverse directly. for(;;) is shorter than while(1>0). No need for a full program, just int c(int a){...} would do as a valid answer, since the question has the following rule: "You may take the input as a function argument. You may return the output from a function." @Emigna is indeed right that the modulo check isn't necessary. \$\endgroup\$ Commented Aug 25, 2016 at 9:18
  • \$\begingroup\$ Oh, and welcome of course! You might like this post: Tips for golfing in Java. \$\endgroup\$ Commented Aug 25, 2016 at 9:19
  • \$\begingroup\$ @Emigna: you're absolutely right, did that. \$\endgroup\$ Commented Aug 25, 2016 at 9:23
  • \$\begingroup\$ @KevinCruijssen: since I only iterate through numbers which are divisible by a (by x += a). I don't have to check for divisibility :) and thanks for the golfing tips! \$\endgroup\$ Commented Aug 25, 2016 at 9:25
7
\$\begingroup\$

C#, (削除) 103 (削除ここまで) 80 Bytes

int f(int p){int x=p;while(x+""!=string.Concat((x+"").Reverse()))x+=p;return x;}

Ungolfed

int f(int p)
{
 int x = p;
 while (x + "" != string.Concat((x + "").Reverse()))
 x += p;
 return x;
}
answered Aug 25, 2016 at 12:54
\$\endgroup\$
2
  • 2
    \$\begingroup\$ You might save some bytes by removing i, and incrementing via x+=p. \$\endgroup\$ Commented Aug 25, 2016 at 15:59
  • 1
    \$\begingroup\$ replacing x.ToString() with 'x+""` will save a bunch of chars. \$\endgroup\$ Commented Aug 25, 2016 at 22:07
6
\$\begingroup\$

Python 2, 46 bytes

f=lambda x,c=0:`c`[::-1]==`c`and c or f(x,c+x)

Ideone it!

Recursive solution with c as counter.

The case for 0 is interesting, because although c=0 satisfies the palindrome condition, it would not be returned, because ccc and 0 or xxx always returns xxx.

answered Aug 25, 2016 at 7:05
\$\endgroup\$
1
  • 1
    \$\begingroup\$ It's a bit shorter to do c*(`c`[::-1]==`c`)or. \$\endgroup\$ Commented Aug 25, 2016 at 18:34
6
\$\begingroup\$

Brachylog, 8 bytes

:L#>*.r=

Try it online! (around 5 seconds for 1234)

Verify all testcases. (around 20 seconds)

:L#>*.r=
?:L#>*.r=. Implicitly filling Input and Output:
 Input is prepended to every predicate,
 Output is appended to every predicate.
?:L *. Input*L is Output,
 L#> L is positive,
 .r . Output reversed is Output,
 =. Assign a value to Output.
answered Aug 25, 2016 at 6:44
\$\endgroup\$
5
\$\begingroup\$

PHP, 39 bytes

while(strrev($i+=$argv[1])!=$i);echo$i;
  • Takes number N as argument $argv[1];
  • ; after while to do nothing
  • strrev return string backward

Same length with for-loop

for(;strrev($i+=$argv[1])!=$i;);echo$i;
answered Aug 25, 2016 at 8:29
\$\endgroup\$
5
\$\begingroup\$

Javascript (ES6), (削除) 55 (削除ここまで) 51 bytes

4 bytes thanks to Neil.

f=(x,c=x)=>c==[...c+""].reverse().join``?c:f(x,x+c)
<input type=number min=1 oninput=o.textContent=this.value%10&&f(+this.value)><pre id=o>

answered Aug 25, 2016 at 7:33
\$\endgroup\$
4
  • \$\begingroup\$ From playing around while creating your code snippet for you, the first + seems unnecessary. \$\endgroup\$ Commented Aug 25, 2016 at 9:51
  • \$\begingroup\$ Would (x,c=x) allow you to avoid the &&c? \$\endgroup\$ Commented Aug 25, 2016 at 9:51
  • \$\begingroup\$ I think you can do c^[...c+""].reverse().join``?f(x,x+c):c to save one more byte. \$\endgroup\$ Commented Aug 25, 2016 at 17:54
  • \$\begingroup\$ c- would work for slightly higher numbers than c^, if necessary. \$\endgroup\$ Commented Aug 25, 2016 at 19:11
4
\$\begingroup\$

Pyke, (削除) 11 (削除ここまで) 9 bytes

.f*`D_q)*

Try it here!

answered Aug 25, 2016 at 7:54
\$\endgroup\$
4
\$\begingroup\$

C, (削除) 217 (削除ここまで) 189 bytes

Standalone version :

int a(char*b){int c=strlen(b);for(int i=0;i<c/2;i++)if(b[i]!=b[c-i-1])return 0;}int main(int e,char **f){int b,c;char d[9];b=atoi(f[1]);c=b;while(1){sprintf(d,"%d",c);if(a(d)&&(c/b)*b==c)return printf("%d",c);c++;}}

Call to a function version :

int s(char*a){int b=strlen(a);for(int i=0;i<b/2;i++)if(a[i]!=a[b-i-1])return 0;}int f(int a){int b;char c[9];b=a;while(1){sprintf(c,"%d",b);if(s(c)&&(b/a)*a==b)return printf("%d",b);b++;}}

Ungolfed :

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int check_palindrome(char *str) {
 int length = strlen(str);
 for (int i = 0; i < length / 2; i++) {
 if (str[i] != str[length - i - 1])
 return 0;
 }
 return 1;
}
int main(int argc, char **argv) {
 int number;
 int pal;
 char string[15];
 number = atoi(argv[1]);
 pal = number;
 while (1) {
 sprintf(string, "%d", pal);
 if (check_palindrome(string) && (pal / number) * number == pal)
 {
 printf("%d\n", pal);
 return 1;
 }
 pal++;
 }
 return 0;
}

Call to a function ungolfed :

int s(char *a) {
 int b = strlen(a);
 for (int i = 0; i < b / 2; i++) {
 if (a[i] != a[b - i - 1])
 return 0;
 }
 return 1; //We can remove it, it leads to a undefined behaviour but it works
}
int f(int a) {
 int b;
 char c[9];
 b = a;
 while (1) {
 sprintf(c, "%d", b);
 if (s(c) && (b / a) * a == b)
 {
 printf("%d\n", b); //no need for the \n
 return 1; //just return whatever printf returns, who cares anyway ?
 }
 b++;
 }
 return 0; //no need for that
}

I included the standalone version for historicity.

This is my first codegolf, any comment is welcome !

\$\endgroup\$
6
  • \$\begingroup\$ I recommend making a separate function for the challenge, and not counting main() regardless of your preferences. You wouldn't play baseball by running twelve loops around first before tagging "because I prefer it," you will never reach safely. This is a competition, and the primary rule is to use any means necessary and legal to reduce byte count. \$\endgroup\$ Commented Aug 25, 2016 at 17:46
  • 1
    \$\begingroup\$ @Snowman fair enouth, I edited my answer to include a 'call to a function' version. This allows me to take an int as parameter and gold away a few more bytes. \$\endgroup\$ Commented Aug 26, 2016 at 9:11
  • \$\begingroup\$ do your function compile without "include <string.h>"? if the answer is not than i can use #define F for or #define R return without make it in count... \$\endgroup\$ Commented Aug 28, 2016 at 8:53
  • \$\begingroup\$ @RosLuP yeah, I get a few warnings but gcc is able to compile it. \$\endgroup\$ Commented Aug 30, 2016 at 9:56
  • \$\begingroup\$ Hi!, I would like drop some Hints! 1) C has implicit int so you can change the code like this int f(int a) -> f(a) 2) if you have to declare some ints you can use the function parameters: int f(int a){int b; -> f(a,b){ 3) sprintf will never return 0 so you ca use in the while: while(1){sprintf(c,"%d",b); -> while(sprintf(c,"%d",b)){ 4) use the K&R C for define a Function so tou can combo with my 2nd hint: int s(char*a){int b=strlen(a);for(int i=0 -> s(a,b,i)char*a;{b=strlen(a);for(i=0; \$\endgroup\$ Commented Jan 4, 2017 at 17:41
4
\$\begingroup\$

R, (削除) 117 (削除ここまで) (削除) 113 (削除ここまで) (削除) 109 (削除ここまで) 101 bytes

D=charToRaw;P=paste;S=strtoi;a=P(i<-scan()+1);while(!all(D(a)==rev(D(a))&&S(a)%%i==0)){a=P(S(a)+1)};a

Ungolfed

i<-scan() #Takes the input
D=charToRaw #Some aliases
P=paste
S=strtoi
a=P(i+1) #Initializes the output
while(!(all(D(a)==rev(D(a)))&&(S(a)%%i==0))) #While the output isn't a palindrom and isn't
 #divisible by the output...
 a=P(S(a)+1)
a

all(charToRaw(a)==rev(charToRaw(a))) checks if at each position of a the value of a and its reverse are the same (i.e., if a is palindromic).
It might be possible to golf out some bytes by messing around with the types.

answered Aug 25, 2016 at 10:17
\$\endgroup\$
4
\$\begingroup\$

Actually, (削除) 15 (削除ここまで) 14 bytes

Asked to answer by Leaky Nun. Golfing suggestions welcome. Try it online!

╖2`╜*$;R=`╓N╜*

Ungolfing

 Implicit input n.
╖ Save n in register 0.
2`...`╓ Push first 2 values where f(x) is truthy, starting with f(0).
 ╜*$ Push register 0, multiply by x, and str().
 ;R Duplicate str(n*x) and reverse.
 = Check if str(n*x) == reverse(str(n*x)).
 The map will always result in [0, the x we want].
N Grab the last (second) value of the resulting list.
╜* Push n and multiply x by n again.
 Implicit return.
answered Aug 25, 2016 at 15:17
\$\endgroup\$
3
\$\begingroup\$

Haskell, (削除) 64 63 (削除ここまで) 56 bytes

x!n|mod x n==0,s<-show x,reverse s==s=x|y<-x+1=y!n
(1!)

Call with (1!)16 or simply 1!16. Try it on Ideone.

answered Aug 25, 2016 at 10:45
\$\endgroup\$
3
\$\begingroup\$

VBSCRIPT, 47 bytes

do:i=i+1:a=n*i:loop until a=eval(strreverse(a))

ungolfed

do #starts the loop
i=i+1 #increments i, we do it first to start at 1 instead of 0
a= #a is the output
n*i #multiply our input n by i
loop until 
a=eval(strreverse(a)) #end the loop when our output is equal to its reverse
answered Aug 25, 2016 at 13:09
\$\endgroup\$
3
\$\begingroup\$

Perl, 25 bytes

Includes +2 for -ap

Run with the input on STDIN:

palidiv.pl <<< 16

palidiv.pl:

#!/usr/bin/perl -ap
$_+="@F"while$_-reverse
answered Aug 25, 2016 at 14:43
\$\endgroup\$
3
\$\begingroup\$

S.I.L.O.S, 109 bytes

readIO 
n = 0
lbla
n + i
a = n
r = 0
lblb
m = a
m % 10
r * 10
r + m
a / 10
if a b
r - n
r |
if r a
printInt n

Try it online!

answered Aug 28, 2016 at 9:04
\$\endgroup\$
3
\$\begingroup\$

Japt, 14 bytes

V±U s w \V?V:ß

Try it online!

Thank you ETHproductions for the help! :)

answered Jan 10, 2017 at 18:46
\$\endgroup\$
3
\$\begingroup\$

Python 2, 44 bytes

x=lambda n,m=0:m*(`m`==`m`[::-1])or x(n,m+n)

Try it online!

I know that the question was posted over six months ago, but this was shorter than any other Python submission.

answered Feb 8, 2018 at 17:57
\$\endgroup\$
1
2
\$\begingroup\$

MATL, 10 bytes

0`G+tVtP<a

Try it online!

0 % Push 0
` % Do...while
 G+ % Add the input. This generates the next multiple of the input
 tV % Duplicate, convert to string
 tP % Duplicate, reverse
 <a % Is any digit lower than the one in the reverse string? This is the
 % loop condition: if true, the loop proceeds with the next iteration
 % End do...while
 % Implicitly display
answered Aug 25, 2016 at 9:57
\$\endgroup\$
2
\$\begingroup\$

PowerShell v2+, 72 bytes

for($i=$n=$args[0];;$i+=$n){if($i-eq-join"$i"["$i".Length..0]){$i;exit}}

Long because of how reversing is handled in PowerShell -- not very well. ;-)

Takes input $args[0], stores into $i (our loop variable) and $n (our input). Loops infinitely, incrementing $i by $n each time (to guarantee divisibility).

Each iteration, we check whether $i is a palindrome. There's some trickery happening here, so let me explain. We first take $i and stringify it with "$i". That's then array-indexed in reverse order ["$i".length..0] before being -joined back into a string. That's fed into the right-hand side of the -equality operator, which implicitly casts the string back into an [int], since that's the left-hand operand. Note: this casting does strip any leading zeros from the palindrome, but since we're guaranteed the input isn't divisible by 10, that's OK.

Then, if it is a palindrome, we simply place $i onto the pipeline and exit. Output is implicit at the end of execution.

Test Cases

PS C:\Tools\Scripts\golfing> 1,2,16,17,42,111,302,1234|%{"$_ -> "+(.\smallest-palindrome-divisible-by-input.ps1 $_)}
1 -> 1
2 -> 2
16 -> 272
17 -> 272
42 -> 252
111 -> 111
302 -> 87278
1234 -> 28382
answered Aug 25, 2016 at 13:27
\$\endgroup\$
2
\$\begingroup\$

MATLAB, 76 bytes

function s=p(n)
f=1;s='01';while(any(s~=fliplr(s))) s=num2str(n*f);f=f+1;end

Call format is p(302) result is a string.

Nothing clever here. It does a linear search, using the num2str() and fliplr() functions.

This ugly arrangement is a touch shorter than using a while(1) ... if ... break end pattern.

Ungolfed

function s = findFirstPalindromeFactor(n)
 f = 1; % factor
 s = '01'; % non-palindromic string for first try
 while( all(s ~= fliplr(s)) ) % test s not palindrome
 s = num2str( n * f ); % factor of input as string
 f = f + 1; % next factor
 end
 
\$\endgroup\$
2
\$\begingroup\$

Mathematica, 49 bytes

(c=#;Not[PalindromeQ@c&&c~Mod~#==0]~While~c++;c)&

Starts the search at c = N, and increments c if not a palindrome and not divisible by N. When conditions are met, outputs c.

answered Aug 25, 2016 at 14:43
\$\endgroup\$
2
\$\begingroup\$

Jelly, 12 bytes

1μ+3ßμDU=Dμ?

Try it online!

Explanation:

This link takes 1 argument. The μs split it into 4 parts. Starting from the last and moving left:

 ? The three parts in front of this are the if, else, and
 condition of a ternary expression.
 DU=D This condition takes a number n as an argument. It converts
 n to an array of decimal digits, reverses that array, and
 then compares the reversed array to the decimalization of
 n (ie is n palindromic in decimal?)
 +3ß This is the else. It adds the original input argument to n
 and then repeats the link with the new value of n.
1 This is the if. It returns the value passed to it.
answered Aug 25, 2016 at 23:21
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 11 bytes \$\endgroup\$ Commented Apr 11, 2018 at 13:10
2
\$\begingroup\$

Elixir, 75 bytes

def f(p,a\0円),do: if'#{a+p}'|>Enum.reverse=='#{a+p}',do: a+p,else: f(p,a+p)
answered Aug 27, 2016 at 23:08
\$\endgroup\$
2
\$\begingroup\$

Python 2, (削除) 66 (削除ここまで) 65 bytes

i is input and x is (eventually) output

def f(i,x):
 y=x if x%i==0&&`x`==`x`[::-1]else f(i,x+1)
 return y

After scrolling through other answers I found a shorter Python 2 answer but I put the effort into my solution so might as well throw it here. ̄\_(ツ)_/ ̄

answered Aug 26, 2016 at 14:11
\$\endgroup\$
2
  • \$\begingroup\$ You can remove the space in [::-1] else. \$\endgroup\$ Commented Aug 26, 2016 at 19:41
  • \$\begingroup\$ can't you remove the assignment of y, and just put the expression on the end of the return? return x if x%i==0&&x==x[::-1]else f(i,x+1), which then means you can make it a lambda, and golf more bytes? \$\endgroup\$ Commented Sep 24, 2016 at 3:01
2
\$\begingroup\$

dc, (削除) 85 (削除ここまで) (削除) 78 (削除ここまで) 76 bytes

[pq]sq?ddsI[dddZ0sR[1-dsD10r^rdsN10%*lR+sRlN10/lDd0<@]ds@xlR++=q+lIrlLx]dsLx

Run:

dc -f program.dc <<< "16"

Output:

272

Previously submitted code and explanation:

 # loads register 'q' with an exit function
[pq]sq
 # register '@' contains an iterative function to reverse a number (312 to 213),
#by calculating one coefficient at a time of the new base 10 polynomial
[1-dsD10r^rdsN10%*lR+sRlN10/lDd0<@]s@
 # register 'L' implements the logic. It iteratively compares the current value
#with the generated reversed one, exiting if equal, otherwise increments the value
#by N and repeats.
[dddZ0sRl@xlR++=q+lIrlLx]sL
 # the "main". It reads the input, then calls the solver function from 'L'.
?ddsIlLx
answered Aug 30, 2016 at 23:50
\$\endgroup\$
2
\$\begingroup\$

REXX, 46 bytes

arg a
do n=a by a until reverse(n)=n
end
say n
answered Jan 4, 2017 at 9:16
\$\endgroup\$
2
\$\begingroup\$

QBIC, 29 bytes

:{c=a*q~!c$=_f!c$||_Xc\q=q+1

Explanation:

: Get cmd line param as number 'a'
{ DO
c=a*q multiply 'a' by 'q' (which is 1 at the start of a QBIC program) and assign to 'c'
~ IF
!c$ 'c' cast to string
= equals
_f!c$| 'c' cast to string, the reversed
| THEN
_Xc Quit, printing 'c'
\q=q+1 ELSE increment q and rerun
 DO Loop is auto-closed by QBIC, as is the IF
answered Jan 10, 2017 at 17:18
\$\endgroup\$
2
\$\begingroup\$

Vyxal, 6 bytes

{:Ḃ≠|+

Try it Online!

Same as my Thunno 2 answer.

Explanation

{:Ḃ≠|+ # Implicit input
{ # While loop
 : # (condition) duplicate current number
 ≠ # not equal to
 Ḃ # its reverse
 |+ # (body) add the input
 # Implicit output
answered Aug 10, 2023 at 9:05
\$\endgroup\$
1
2

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.