Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Write a program that reads from stdin two integers, each newline terminated, hereafter called "number" and "radix", and:

  1. Prints any fixed message you want if the number is a palindrome in that radix (e.g. true, t, 1)
  2. Prints any different fixed message you want if the number is not a palindrome in that radix (e.g. false, f, 0, etc.)
  3. These messages must be the same per each run, but there are no rules about what they must be (whatever's best for golfing).
  4. You may assume the input is valid, two positive integers. "number" will not exceed 2147483647, "radix" will not exceed 32767.
  5. You may not use external resources, but you may use any math function included by default in your language.

Note: a radix is just the base of the number.

Sample runs:

16
10
false

16
3
true

16
20
true

121
10
true

5
5
false

12346
12345
true

16781313
64
true

16781313
16
true
share|improve this question
    
Note: a radix is just the base of the number. –  hosch250 Feb 28 at 21:32
    
Looks good now. You may want to ban external resources though. –  hosch250 Feb 28 at 21:35
    
@user2509848 hmmm, for instance? –  durron597 Feb 28 at 21:38
    
If a person can find a calculator on the web that converts numbers between bases, it will almost certainly be used. We have been having a rash of trolly answers lately. –  hosch250 Feb 28 at 21:40
add comment

14 Answers

up vote 5 down vote accepted

J (23 char) and K (19) double feature

The two languages are very similar, both in general and in this specific golf. Here is the J:

(-:|.)#.^:_1~/".1!:1,~1
  • ,~1 - Append the number 1 to itself, making the array 1 1.
  • 1!:1 - Read in two strings from keyboard (1!:1 is to read, and 1 is the file handle/number for keyboard input).
  • ". - Convert each string to a number.
  • #.^:_1~/ - F~/ x,y means to find y F x. Our F is #.^:_1, which performs the base expansion.
  • (-:|.) - Does the argument match (-:) its reverse (|.)? 1 for yes, 0 for no.

And here is the K:

a~|a:_vs/|.:'0::'``
  • 0::'`` - Read in (0::) a string for each (') line from console (` is the file handle for this).
  • .:' - Convert (.:) each (') string to a number.
  • _vs/| - Reverse the pair of numbers, so that the radix is in front of the number, and then insert (/) the base expansion function _vs ("vector from scalar") between them.
  • a~|a: - Assign this resulting expansion to a, and then check if a matches (~) its reverse (|). Again, 1 for yes, 0 for no.
share|improve this answer
    
+1; you could have submitted 2 answers for 2 different languages. –  ak82 Mar 1 at 13:37
    
@ak82 I believe it's more interesting this ways –  Jan Dvorak Mar 1 at 17:32
add comment

GolfScript, 10 characters

~base.-1%=

That is an easy one for GolfScript if we do it the straightforward way. The output is 0/1 for false/true.

~       # Take input and evaluate it (stack: num rdx)
base    # Fortunately the stack is in the correct order for
        # a base transformation (stack: b[])
.       # Duplicate top of stack (stack: b[] b[])
-1%     # Reverse array (stack: b[] brev[])
=       # Compare the elements
share|improve this answer
add comment

APL (20)

⎕{≡∘⌽⍨⍵⊤⍨⍺/⍨⌊1+⍺⍟⍵}⎕

Outputs 0 or 1, e.g:

      ⎕{≡∘⌽⍨⍵⊤⍨⍺/⍨⌊1+⍺⍟⍵}⎕
⎕:
      5
⎕:
      5
0
      ⎕{≡∘⌽⍨⍵⊤⍨⍺/⍨⌊1+⍺⍟⍵}⎕
⎕:
      16781313
⎕:
      64
1

Explanation:

  • ⎕{...}⎕: read two numbers, pass them to the function. is the first number and is the second number.
  • ⌊1+⍺⍟⍵: floor(1+⍺ log ⍵), number of digits necessary to represent in base .
  • ⍺/⍨: the base for each digit, so replicated by the number we just calculated.
  • ⍵⊤⍨: represent in the given base (using numbers, so it works for all values of ).
  • ≡∘⌽⍨: see if the result is equal to its reverse.
share|improve this answer
add comment

Sage, 45

Runs in the interactive prompt

A=Integer(input()).digits(input())
A==A[::-1]

Prints True when it is a palindrome, prints False otherwise

share|improve this answer
add comment

Perl, 82 77 73 69 bytes

$==<>;$.=<>;push(@a,$=%$.),$=/=$.while$=;@b=reverse@a;print@a~~@b?1:0

The input numbers are expected as input lines of STDIN and the result is written as 1 or 0, the former meaning the first number is a palindrome in its representation of the given base.

Edit 1: Using $= saves some bytes, because of its internal conversion to int.

Edit 2: The smartmatch operator ~~ compares the array elements directly, thus the conversion to a string is not needed.

Edit 3: Optimization by removing of an unnecessary variable.

65 bytes: If the empty string is allowed as output for false, the last four bytes can be removed.

Ungolfed version

$= = <>;
$. = <>;
while ($=) {
    push(@a, $= % $.);
    $= /= $.; # implicit int conversion by $=
}
@b = reverse @a;
print (@a ~~ @b) ? 1 : 0

The algorithm stores the digits of the converted number in an array @a. Then the string representation of this array is compared with the array in reverse order. Spaces separates the digits.

share|improve this answer
    
Sorry, my answer is really same aproach, but using $= let you whipe int step... And question stand for anything you want so nothing could be what you want ;-) –  F. Hauri Feb 28 at 23:10
    
@F.Hauri: Thanks, I will update. $= is also given as tip in this answer to the question "Tips for golfing in Perl". Returning 0 costs 6 extra bytes, but it was my impression that a fixed message is not intended to be empty. –  Heiko Oberdiek Feb 28 at 23:27
    
Hem,, Return 0 cost 4 extra bytes, not 6. But I maintain: silence is anything! –  F. Hauri Feb 28 at 23:34
    
@F.Hauri: Yes, 4 is correct, the extra two bytes were the parentheses of the ungolfed version. –  Heiko Oberdiek Feb 28 at 23:44
add comment

Perl 54 56 62

$==<>;$-=<>;while($=){$_.=$/.chr$=%$-+50;$=/=$-}say$_==reverse

To be tested:

for a in $'16\n3' $'16\n10' $'12346\n12345' $'12346\n12346' $'21\n11' $'170\n16';do
    perl -E <<<"$a" ' 
        $==<>;$-=<>;while($=){$_.=$/.chr$=%$-+50;$=/=$-}say$_==reverse
    '
  done

will give:

1

1


1

So this output 1 for true when a palindrome is found and nothing if else.

Ungolfing:

$==<>;                            # Stdin to `$=`  (value)
$-=<>;                            # Stdin to `$-`  (radix)
while ( $= ) {
    $_.= $/. chr ( $= % $- +50 ); # Add *separator*+ chr from next modulo to radix to `$_`
    $=/= $-                       # Divide value by radix
}
say $_ == reverse                 # Return test result

Nota:

  • $_ is the current line buffer and is empty at begin.
  • $= is a reserved variable, originaly used for line printing, this is a line counter. So this variable is an integer, any calcul on this would result in a truncated integer like if int() was used.
  • $- was used for fun, just to not use traditional letters... (some more obfuscation)...
share|improve this answer
    
to clarify, this says nothing when it's not a palindrome, and 1 when it is? –  durron597 Feb 28 at 23:08
1  
Nice tricks. However wrong positive: 21 with base 11. The digits need a separator in the string comparison. –  Heiko Oberdiek Feb 28 at 23:15
    
Aaaarg +3! @HeikoOberdiek You're right f... –  F. Hauri Feb 28 at 23:27
    
@F.Hauri: Also the digits get reversed. Thus 170 with base 16 is 0xAA, a palindrome, but the result is false. –  Heiko Oberdiek Feb 28 at 23:53
    
Aaarg +6! converting to chars... –  F. Hauri Mar 1 at 8:52
add comment

Javascript 87

function f(n,b){for(a=[];n;n=(n-r)/b)a.push(r=n%b);return a.join()==a.reverse().join()}

n argument is the number, b argument is the radix.

share|improve this answer
add comment

Mathematica 77 43

IntegerDigits[n,b] represents n as a list of digits in base b. Each base-b digit is expressed decimally.

For example, 16781313 is not a palindrome in base 17:

IntegerDigits[16781313, 17]

{11, 13, 15, 11, 14, 1}

However, it is a palindrome in base 16:

IntegerDigits[16781313, 16]

{1, 0, 0, 1, 0, 0, 1}


If the ordered pairs in the above examples were entered,

(x=Input[]~IntegerDigits~Input[])==Reverse@x

would return

False (* (because {11, 13, 15, 11, 14, 1} != {1, 14, 11, 15, 13, 11} ) *)

True (* (because {1, 0, 0, 1, 0, 0, 1} is equal to {1, 0, 0, 1, 0, 0, 1} ) *)

share|improve this answer
    
Weird, not necessary for the answer but I'm curious, how does it render them? –  durron597 Feb 28 at 23:20
    
I hate it when I lose because of a stupid typecast... –  ace Feb 28 at 23:20
    
Kindly explain "typecast". –  David Carraher Feb 28 at 23:50
    
My sage solution is longer than yours by 2 characters because I have to cast the input to type Integer –  ace Mar 1 at 0:44
    
Now I understand what you mean. Thanks. –  David Carraher Mar 1 at 10:26
show 1 more comment

Haskell (80 chars)

tb 0 _=[]
tb x b=(tb(div x b)b)++[mod x b]
pali n r=(\x->(x==reverse x))(tb n r)

Call it with pali $number $radix. True, when number is a palindrome, False if not.

share|improve this answer
add comment

dg - 97 bytes

Trying out dg:

n,r=map int$input!.split!
a=list!
while n=>
 a.append$chr(n%r)
 n//=r
print$a==(list$reversed a)

Explained:

n, r=map int $ input!.split!      # convert to int the string from input
a = list!                         # ! calls a function without args
while n =>
 a.append $ chr (n % r)           # append the modulus
 n //= r                          # integer division
print $ a == (list $ reversed a)  # check for palindrome list
share|improve this answer
add comment

C, 140 132

int x,r,d[32],i=0,j=0,m=1;main(){scanf("%d %d",&x,&r);for(;x;i++)d[i]=x%r,x/=r;i--;for(j=i;j;j--)if(d[j]-d[i-j])m=0;printf("%d",m);}
  • radix 1 is not supported:)
share|improve this answer
1  
Just puts(m) would work right? –  durron597 Mar 2 at 11:50
    
printf("%d",m); will be by 8 characters shorter. –  V-X Mar 2 at 13:03
add comment

Haskell - 59

Few changes to Max Ried's answer.

0%_=[]
x%b=x`mod`b:((x`div`b)%b)
p=((reverse>>=(==)).).(%)
share|improve this answer
add comment

Ruby - 76 chars

f=->(n,b){n==0?[]:[n%b,*f.(n/b,b)]};d=f.(gets.to_i,gets.to_i);p d==d.reverse
share|improve this answer
add comment

Java - 212 chars (which is a palindrome in base 10)

import java.util.*;public class RP{public static void main(String[] args){Scanner s=new Scanner(System.in);String n=Integer.toString(s.nextInt(),s.nextInt());System.out.print(new StringBuilder(n).reverse().toString().equals(n));}}

Since it is Java, I don't expect to win but it was too easy to write so I couldn't resist.

Ungolfed:

import java.util.*;

public class RP {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String n = Integer.toString(s.nextInt(),s.nextInt());
        System.out.print(new StringBuilder(n).reverse().toString().equals(n));
    }
}

It works for all given examples with radix <= 36 (which is MAX_RADIX in Integer).

share|improve this answer
    
I know about this solution, that's why I made radix be higher than 36 –  durron597 Feb 28 at 22:29
    
Sorry, I was wrong. –  Wally Mar 1 at 4:53
    
@Wally would you like to delete your answer, then? –  Jan Dvorak Mar 1 at 5:29
    
@JanDvorak My comment was wrong, which I deleted. It was also inflammatory - which is why I also apologized to durron597. Nothing is wrong with my answer except the base limitation, which I advertised. I suppose that limitation is the source of the down votes - which are a legitimate expression of opinion. –  Wally Mar 1 at 14:35
    
@Wally indeed. The spec explicitly states that bases until 32k must be supported, which means your entry doesn't satisfy the spec. –  Jan Dvorak Mar 1 at 16:08
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.