# Question
Title: How do I find the longest palindrome in a string?
The challenge:

> Make a function that finds the longest palindrome inside a string.

Note: This is a question. Please do not take the question and/or answers seriously. More information here.

# Answer
> 18 votes
# Go

The following solution in Go employs the hidden powers of concurrency, closures and recursivity to find the longest palindrome inside a given string:

```
func lp(s string) string {
    for i, l := 0, len(s); i < l; i++ {
        if s[i] != s[l-i-1] {
            a, b := make(chan string), make(chan string)
            go func() {
                a <- lp(s[:l-1])
            }()
            go func() {
                b <- lp(s[1:])
            }()
            c, d := <-a, <-b
            if len(c) > len(d) {
                return c
            }
            return d
        }

    }
    return s
}

```

Additionally, it relies entirely on language primitives and built-in types – no standard library – that's how you recognize true quality software.

You might want to turn your thread, memory and stack size limits up a bit for larger input strings – this is because this solution is so fast that your OS will get all jealous on it.

Edit – Perks:

* totally useless on multibyte character strings.
* will not omit punctuation or whitespace characters.
* omits upper/lower-case equality.
* runs in a hard to calculate time – very slow, though.
* spawns lots and lots of goroutines, depending upon input.
* gets killed for memory exhaustion after couple of seconds on my machine with ~~over 16000~~ 2049186 goroutines spawned for the input `"345345ABCDEabcde edcbaDEABC12312123"`

# Answer
> 45 votes
## Python

```
def longest_palindrome(s):
    return 'racecar'

```

Example usage:

```
>>> print longest_palindrome('I like racecars!')
racecar

```

Note: this may only work for certain strings.

# Answer
> 13 votes
Clearly, checking for Palindromes is hard.

So the solution is pretty simple - generate a set of every single possible Palindrome as large as the string you're testing, and see if your string contains it.

C#

```
string largest = String.Empty;

    for(int i=0; i < myString.lenght; i++)
    {

//Don't use the newfangled stringbuilder. Strings are awesome
char[] testString = new char[i];

    for (int charPosition=0; charPosition < i/2; charPosition++)
    {
    for (char c = 'A'; c <= 'Z'; c++)
    {
       if ((charPosition/i) == i/2)
{
//middle one
testString[i] = c;
}
else
{
//do one for that position, and the lenght-position
testString[i] = c;
testString[testString.length - i] = c;
}

if (myString.Contains(testString.ToString())
{
//yaay
largest = testString.ToString();
}

{

}
    }

}

}

```

(I might need to check my code for correctness, but otherwise its a wonderfully horribly inefficient way to check for Palindromes)

# Answer
> 12 votes
# Perl

Does everything asked for. It is actually better, because it takes into account every possible *subsequence*. What's the catch? It operates in exponential time, so each additional character in the string doubles the running time. Give it more than 20 characters, and it will take all day.

```
$inputstring = <>;
@arrayofcharacters = split("",$inputstring);
for(0..2**length($inputstring)-1){
 $currentsubsequence = "";
 @choice=split("",sprintf("%b",$_));
 for(0..$#arrayofcharacters){
  $currentsubsequence .= "$arrayofcharacters[$_]" x $choice[$_];
  if($currentsubsequence eq reverse($currentsubsequence)){
   $palindromes{length($currentsubsequence)} = $currentsubsequence;
   $palindromes[~~@palindromes] = length($currentsubsequence);
  }
 }
}
print($palindromes{@{[sort(@palindromes)]}[$#palindromes]})

```

Input: `iybutrvubiuynug`. Output: `ibutubi`.

Input: `abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba`. Output: won't happen

# Answer
> 9 votes
Your problem is easily solved by regular expressions, just like in the picture below (but I decided to use java instead). This happens because regex is always the best tool that may be used for anything that involves extracting or analyzing text.

```
package palindrome;

import java.util.regex.Pattern;
import javax.swing.JOptionPane;

public class RegexPalindrome {

    private static String next(String now) {
        if (now.isEmpty()) return "a";
        String prefix =  now.length() == 1 ? "" : now.substring(0, now.length() - 1);
        if (now.endsWith("z")) return next(prefix) + "a";
        return prefix + String.valueOf((char) (now.charAt(now.length() - 1) + 1));
    }

    public static void main(String[] args) {
        String text = JOptionPane.showInputDialog(null, "Type some text:");

        String bestPalindromeFound = "";

        for (String searchText = "a"; searchText.length() <= (text.length() + 1) / 2; searchText = next(searchText)) {
            String reverse = new StringBuilder(searchText).reverse().toString();
            if (searchText.length() * 2 - 1 > bestPalindromeFound.length()) {
                Pattern p = Pattern.compile(".*" + searchText + reverse.substring(1) + ".*");
                if (p.matcher(text).matches()) bestPalindromeFound = searchText + reverse.substring(1);
            }
            if (searchText.length() * 2 > bestPalindromeFound.length()) {
                Pattern p = Pattern.compile(".*" + searchText + reverse + ".*");
                if (p.matcher(text).matches()) bestPalindromeFound = searchText + reverse;
            }
        }
        JOptionPane.showMessageDialog(null, "The longest palindrome is \"" + bestPalindromeFound + "\".");
    }
}

```

---

This code is evil because:

* It runs in exponential time to the size of the given text. It runs by enumerating all the strings in the form a-z, creating two regexes for each generated string and testing the input against each regex.
* Further, it fails if the palindrome contains uppercase letters, numbers, non-ascii text, punctuation, etc.
* And of course, regex is clearly not the right tool for that.

# Answer
> 7 votes
# **Python**

This takes the string, and reorganises it to the longest possible palindrome available.

For example:

Input : Hello

Ouput : lol

```
def get_palindrome(string):
    if len(string) == 0:
        return "I didn't catch that"
    list_of_characters = []
    occurances = []
    for character in string:
        if not character in list_of_characters:
            list_of_characters.append(character)
            occurances.append(1)
        else :
            occurances[list_of_characters.index(character)] +=1
    #check if a palindrome is possible
    if sum(occurances) == len(occurances): #no double letters, so only a one character palindrome
        return list_of_characters[0]
    first_half = ''
    second_half = ''
    middle_character = ''
    for index, character in enumerate(list_of_characters):
        number_of_occurances = occurances[index]/2
        first_half += character * number_of_occurances
        second_half = (character * number_of_occurances)+ second_half
        if (occurances[index]%2 != 0):#if there are an odd number, there will be one spare,
            #so put it in the middle
            middle_character = character
    return first_half + middle_character + second_half

print(get_palindrome(raw_input("String containing palindrome:")))

```

# Answer
> 6 votes
## Python

```
def get_substrings(a_string):
    """Get all possible substrings, including single character substrings"""
    for start_index in range(len(a_string)):
        for end_index in range(start_index + 1, len(a_string) + 1):
            yield a_string[start_index:end_index]

def get_longest_palindrome(a_string):
    """Find the longest palindrome in a string and return its index or -1"""

    # Initialise variables
    longest_palindrome = get_longest_palindrome.__doc__[5:27]
    palindromes_list = []

    # Search string for all palindromes
    for substring in get_substrings(a_string):
        if reversed(substring) == substring:
            palindromes_list.append(substring)

    # There should always be palindromes in non-empty strings (single characters),
    # but it's good practice to check anyway
    if len(palindromes_list) > 0:
        longest_palindrome = max(palindromes_list, key=len)

    return a_string.find(longest_palindrome)

```

The string "the longest palindrome" is extracted from the docstring into `longest_palindrome`.

The `reversed()` function returns an iterator, so `reversed(substring) == substring` will never be true and `longest_palindrome` will never be overwritten.

Hence, the function will literally find "the longest palindrome" inside a string.

# Answer
> 6 votes
### bioinformatics interpretation

Very cool question dude!

Palindromes in normal language are not entirely clearly specified, for example if spaces are allowed or not. So it is not clear if these should be allowed as palindromes or not:

* Do geese see God?
* A man, a plan, a canal--Panama!

Anyway, I think you are referring to the better specified scientific meaning of palindrome: For a nucleotide sequence to be considered as a palindrome, its complementary strand must read the same in the opposite direction. Both the strands i.e the strand going from 5' to 3' and its complementary strand from 3' to 5' must be complementary (see here).

There is some research done for palindrome sequence recognition and I think you should really read at least this. To solve your problem you can pretty much just copy their approach! The professor even sends out the source code if you ask him.

Well, now to the problem at hand. Suppose you have a nucleotide sequence given as a character string. The best way to find palindromes in such a sequence is by using standard algorithms. I think your best bet is probably using this online tool: http://www.alagu-molbio.net/palin.html

Since you are required to provide a function that does the task, you need to think about how to get your string into this app? Well, there the fun begins. I think you could use selenium for that. Since I don't want to do your homework, i just give you the basic idea. In Java you world start like this:

```
package testing;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;

public class PalindromeService {

    public static void main(String[] args) {
        WebDriver d1 = new PhantomJSDriver();

        d1.get("http://www.alagu-molbio.net/palin.html");

        String sequence = "AAGTCTCGCGAGATCTCGCGAGATCTCGCGAGATCTCGCGAGAAA";

        WebElement txtArea = d1.findElement(By.tagName("textarea"));

        txtArea.sendKeys(sequence);

        WebElement send = d1.findElement(By.cssSelector("input[type=submit]"));
        send.click();

        String result = d1.findElement(By.tagName("body")).getText();

        Pattern p = Pattern.compile(".*capitalized\\.[^agctACGT]*([agctACGT]+).*");
        Matcher m = p.matcher(result);
        if (m.find()){
            result = m.group(1);
        }

        //now you have all palindromes in upper case!
        //I think you can take it from here, right?

        System.out.println(result);

        d1.quit();
    }
}

```

In case you are interested in language palindromes you can use the same technique with other web services like http://www.jimsabo.com/palindrome.html or http://calculator.tutorvista.com/math/492/palindrome-checker.html

### code-trolling technics

* omit the truely helpful sources like http://rosettacode.org/wiki/Palindrome\_detection
* interesting but unhelpful blah about bioinformatics
* deliberately misunderstanding this as bioinformatics task
* cheating - to solve the problem a web service is used

# Answer
> 5 votes
# Javascript

Oh, thats easy ;). Here ya go:

```
function () {
    var palidrome = "Star? Not I! Movie – it too has a star in or a cameo who wore mask – cast are livewires.

Soda-pop straws are sold, as part-encased a hot tin, I saw it in mad dog I met. Is dog rosy? Tie-dye booths in rocks.

All ewes lessen ill. I see sheep in Syria? He, not I, deep in Syria, has done. No one radio drew old one.

Many moths – I fondle his; no lemons are sold. Loot delis, yob, moths in a deli bundle his tin. Pins to net a ball I won – pins burst input. I loot to get a looter a spot paler. Arm a damsel – doom a dam. Not a base camera was in a frost, first on knees on top spot. Now a camera was a widened dam.

Ask: Cold, do we dye? No, hot – push tap, set on to hosepipe. Nuts in a pod liven.

A chasm regrets a motto of a fine veto of wars. Too bad – I all won. A sadist sent cadets – a war reign a hero derides. A bad loser, a seer, tossed a cradle – he begat to cosset – a minaret for Carole, Beryl, Nora. We’re not as poor to self.

I risk cold as main is tidal. As not one to delay burden, I don’t set it on “hot”. A foot made free pie race losses runnier. As draw won pull, eye won nose. Vile hero saw order it was in – even a moron saw it – no, witnessed it: Llama drops – ark riots. Evil P.M. in a sorer opus enacts all laws but worst arose. Grab a nosey llama – nil lesser good, same nicer omen.

In pins? No, it is open. If a top spins, dip in soot.

Madam, as I desire, dictates: Pull aside, damsels, I set a rag not for a state bastion. A test I won e.g. a contest I won.

Kidnap, in part, an idle hero. Megastars, red, rosy, tied no tie. Blast! A hero! We do risk a yeti’s opposition!

He too has a wee bagel still up to here held.

Demigods pack no mask, cap nor a bonnet, for at last a case is open – I left a tip – it wets. A dog wets too. Radios to help pay my tip, pull a tip.

Ale, zoo beer, frets yon animal. Can it? New sex arose but, we sots, not to panic – it’s ale – did I barrel? Did I lose diadem, rare carrot in a jar of mine? Droop as tops sag – unseen knots.

A cat ate straw as buck risk cud; evil foe, nil a red nag ate? Bah! Plan it – silage. Model foot in arboreta.

I, dark Satanist, set fire – voodoo – to slat. I design a metal as parrot, I deem it now. One vast sum is no ten in set – amen! Indeed, nine drag a yam, nine drag a tie. Dame nabs flower; can we help man? Woman is worse nob.

Mud level rose, so refill a rut. A nag of iron I made to trot I defied – I risk leg and its ulnae. Can a pen I felt to bid dollar or recite open a crate, open a cradle, his garret?

Sample hot Edam in a pan. I’m a rotten digger – often garden I plan, I agreed; All agreed? Aye, bore ensign; I’d a veto – I did lose us site. Wool to hem us? No, cotton. Site pen in acacias or petals a last angel bee frets in.

I met a gorilla (simian); a mate got top snug Noel fire-lit role. Manet, Pagnol, both girdle his reed bogs.

Flan I reviled, a vet nods to order it, Bob, and assign it. Totem users go help mates pull as eye meets eye. Son – mine – pots a free pie, yes? No. Left a tip? Order a dish to get. A ring is worn – it is gold. Log no Latin in a monsignor, wet or wise. Many a menu to note carrot.

Cat in a boot loots; As I live, do not tell! A bare pussy, as flat on fire, I know loots guns, fires a baton, nets a hero my ale drop made too lax.

If it is to rain, a man is a sign; I wore macs, no melons rot. I use moths if rats relive, sir, or retire.

Vendor pays: I admire vendee, his pots net roe. Nine dames order an opal fan; I’ll ask cold log fire vendor to log igloo frost. Under Flat Six exist no devils.

Marxist nods to Lenin. To Lenin I say: “Mama is a deb, besides a bad dosser.”

Gen it up to get “ova” for “egg”. I recall a tarot code: yell at a dessert side-dish sale. Yes/nos a task cartel put correlate: E.S.P. rocks a man. I am a man, am no cad, I’m aware where it’s at!

Fire! Its an ogre-god to help, man, as I go. Do not swap; draw, pull a troll!

It’s not a cat I milk – calf, for a fee, sews a button – knit or tie damsel over us. Mined gold lode I fill until red nudes I met in a moor-top bar can. I sit, I fill a diary – trap nine men in ten-part net – oh, sir, I ask, cod nose? No, damp eel.

So, to get a name! I say, Al! I am Al! Last, I felt, to breed, deer begat.

To can I tie tissue – damp – or deliver Omani artist – a man of Islam.

In a den mad dogs lived on minis a signor who lived afore targets in at. As eremites pull, I, we, surf, fantasise, mend a bad eye. No hero met satyr; Tony, as I stressed, won’t, so cosset satyr.

A vet on isles made us sign it, a name. Foe man one sub.

Aside no dell I fret a wallaby; metal ferrets yodel, like so. On a wall I ate rye. Bored? No, was I rapt! One more calf? O.K., calf, one more, bossy! No! Lock cabin, rob yam, sip martini. Megastar was in a risk.

Cat? No, I’m a dog; I’m a sad loyal pet. A design I wore – kilts (a clan); if net drawn, I put it up. Royal spots snag – royal prevents rift.

Composer, good diet, are both super, God – label it a love of art, lustre. Video bored, no wise tale e.g. a mini tale – no sagas seen. Knack: cede no foes a canal.

Pay – as I sign I lie; clear sin it is; e.g. “Amadeus” sign I – lira for ecu, decimal – sin as liar.

Trad artistes pull a doom, a drawer won’t.

Is it sold loot? No, I suffered loss. A man is god; Amen! I came nice Tahiti (sic).

It’s ale for a ban if for a fast – is role to help mash turnip? Use zoo? No – grasp order – use no zoos. Warts on time did sag.

No grade “X” “A” Level? Oh, “A”! I’d a “B” or a “C”. So – pot? No, we lop. Date? Take no date! Bah! Play L.P.

Miss (a lass, all right?) flew to space in NASA era. Rose no (zero) cadets ate raw. As a wise tart I fined rags red Lenin, we help pay bet – a risk – cash to Brian. I put a clam in a pool – a pool wets.

Mahdi puts a stop to harem – miss it in one vote, lost in one, veto of none. Post-op, no tonsil; I ate; no tastier, eh? We sleep at noon time so I dare not at one; no time stops as I time tides. A bed: under it, roll; in a mania, panic!

In a pond I did as Eros as Lee felt tenrec. “Ink” – list it under “I”. Termites put pen in a way. Democrats wonder, I too. To slay moths a dog did.

I saw elf; elf, far now, is a devilish taboo, rag-naked. I hid a bootleg disc. I, saboteur, toss it in. Oops! No legs! Laminated, a cask, conker in it, negates all if it is simple.

Hot pages are in a mag, nor will I peer, familiar tat, so lewd, native rot. Toner, ewe wore no trace; vagabond ewes do. Oh, Ada! Have pity! A pitiable eel – “Oh wet am I!” – to save, note: bite gill as I do.

Call a matador minor, eh? As I live, don’t! Is torero no rigid animal debaser if tipsy? Ale drew esteem in a matador. A bolero, monks I rate play or go dig rocks; a can I step on.

Go! Gas – it evades a bedsit – set a roost on fire. Boss sent a faded eclair to green imp or dog, I’d don a belt to boot it; if Ada hid a boot, panic.

I mock comic in a mask, comedian is a wit if for eventide. Vole no emu loved is not a ferret, so pet or witness a weasel if not. I hired less, am not so bossy, as yet amateur.

To stir evil, Edna can impugn a hotel: bad loos, hot on Elba: I may melt. Tart solicits it rawer, gets it rare. Push crate open; I ram buses, use no trams.

Did I say, not to idiot nor a bare ferret, to trap rat, strap loops rat? Stewpot was on. Hot? I was red! Lessen it! Fine man on pot? No, pen inside by a bad law. So I made rips – nine delays.

Some Roman items in a.m. ordered “Is room for a ban?” “It is,” I voted: I sat pews in aisle. Beryl, no tiro to my burden, made off for a contest, I won kiss. I may raid fine dales. I raid lochs if I to help am.

Forecast for Clare v. Essex: If no rain, a man is ref. Fusspots net foxes.

Senor is a gnome, latinos’ bad eyesore. Help misses run to border, Casanova, now, or drab hotel.

Ma has a heron; I sleep, pet’s on nose, sir! Rev. I rag loved art live – fine poser. Ultra-plan: I feign, I lie: cedar to disperse – last one? No, last six. Enamel bonnet for a dark car to toss a snail at. In it all, Eve lost; Seth’s a hero slain on a trap – Rise, Sir Ogre Tamer.

Upon Siamese box I draw design. I, knight able to help, missed an alp seen in Tangier of fine metal pots. Tin I mined rages – order nine, melt ten. Tone radios; tones are not to concur. Ten-tone radar I bomb – best fire-lit so hostel side meets eerie mini red domicile. A gulf to get is not a rare tale; no time to nod.

Row on, evil yobs, tug, pull. If dogs drowse, fill a rut. An era’s drawers draw. Put in mid-field in a band I dig a tub deep. Staff on a remit did refill a minaret.

Sam’s a name held in a flat, or, sir, bedsit. I wonder, is it illicit ore? No ties? A bit under? Retarded? Is ‘owt amiss? I’m on pot; not so Cecil, a posh guy a hero met. A red date was not to last so Cecil sat.

Tip? An iota to pay, a dot; sad, I drop item. I’d ask, call, Odin, a Norseman’s god: “Pay payee we owe radio dosh o.n.o.” I to me? No, I to media.

Peril in golf – is ball a “fore”? K.O.!

Vexed I am re my raw desires. Alto has eye on nose but tone-muser pianist is level-eyed. I lost a tie. Blast! In uni no grades are musts. Avast! Never port! Sea may be rut.

Part on rose? – It’s a petal. Define metal:

Tin is . (I gulp!) can!

I am a fine posse man, I pull a ton. Ron, a man I put on, I made suffer of evil emu’s sadism. Leo’s never a baron – a bad loss but evil – topple him, Leo’s lad. Assign a pen, can I? A pal is note decoding.

Is damp mule tail-less? No, ill; I breed for its tone. Radio speed, to grower, grew. Open a lot? No, stamp it; if for a free peso – not ecu -deign it. Times ago stone rates, e.g. at Scilly, display a wont.

No wish to get a design I, Sir Des, I’ve let? No bus sees Xmas fir. O.K. – cab – tart it up; tie lots – diamond, log or tinsel; first end errata edit. So “le vin (A.C.)”, Martini, Pils lager, one tonic.

I pegged a ball up to here when I got a top star role, Beryl. Gun is too big – won’t I menace? Yes? No?

Ill? A cold? Abet icecap’s nip. U.S.A. meets E.E.C. inside tacit sale – see! Beg a cotton tie, ma! No trial, so dodo traps exist. Arabs under-admire card label good hood stole.

In rage erupted Etna. Will a rotunda, bare villa, to tyro. Lack car? Non-U! Get a mini! My, my, Ella, more drums per gong; get a frog – nil less. Rod, never ever sneer. Got to?

I disperse last pair of devils (ah!) here today or else order cash to breed emus. Said I: “Are both superlative?” C.I.D. assign it lemon peel still. I wore halo of one bottle from a ref (football) – a tip; so hit last ego slap a mate got.

Late p.m. I saw gnu here (non-a.m.) or an idea got a dog to nod – I made felt to boot.

Fill in a lad? Nay, not all, Edna – lash to buoy. Did you biff one Venus? Not I! “Broth, girl!” ladies ordered – “No, with gin!” – a fine plate, maybe suet; no carton I made rots in it.

Med: a hill, Etna, clears in it. Ali, Emir, to slap in/slam in. All in all I made bad losers sign it – alibi. Set a lap for a level bat.

A bed, sir, eh? To put cat now? Drat! Such an idyll of a dog’s lair! That`s it, open it – a cage! Big nit sent rat! Some day (A.D.) send ewe. No, draw a pot now, do! Of wary rat in a six ton tub.

Edna, ask satyr: “Tel. a.m.?” No, tel. p.m.; Israeli tuner is damp. Use item: “Anna Regina”. No! Dye main room (“salle”) red!

Nice caps for a sea cadet in U.S.A. – Now I, space cadet, am it, sea vessel rep. Pin it on Maria, help Maria fondle her fine hotpot. No! Meet; set up to net, avoid a lesion. Set acid arena: Bruno one, Reg nil. Like it to sign in? Even I am nine-toed! I vote votes.

Oh, can a nose-rut annoy? No, best is Dorset. I know, as liar, to snoop, malign. “I’ll order it to get a bedroom door,” began a miser I fed.

Am I to peer, fan? Is a door by metal? Ere sun-up, drowse, nod, lose magnet. Food? Buns? I’ll ask. Corn? I’ll ask. Corn – I snack. Cats snack (cold rat). Sum for a bag: nil. First, is remit “traps in net”? Yes, on a par. Coots yell over a dam I made. Bared nudist went a foot, I made roots. I tip a canon: “Row, sir, at same tide; man one: row tug.”

Sewer of denim axes a wide tail – a terror recipe to hero made manic. I, to resign? I ? Never!

“OFT I FELT ITS SENSUOUSNESS” – title fit for evening is erotic; I named a more hot epic – error retaliated – I was examined for ewe’s gut, wore no named item.

A star is worn on a cap, it is too red. Am I too fat? Newts I’d under a bed. Am I mad? Are volleys too crap? A nosey tennis part-timer sits rifling a bar of mustard.

Lock cans, stack cans in rocks, all in rocks, all I snub. Do often games, old ones, word-pun use; relate, my brood, as in a free pot I made fires, I manage brood. Moor debate got tired rolling, I lampoon, so trail saw on kites.

Rod sits, ebony on nature, so Nana chose to veto video. Ten in main evening is O.T.T. i.e. killing; Ere noon, urban eradicates noise, lad, I ovate not. Put esteem on top (to hen, if reheld).

No fair ample hair – am not I nipper-less? Eva estimated ace caps I won as united. A Caesar of space, Cinderella’s moor, Niamey Don (a Niger-an name), ties up mad sire, nut! I, Lear, simpleton male, try tasks “A” and “E”

but not “XI”. Sanitary raw food won top award one Wednesday – a demo.

Start nesting, I beg a cat. I? Nepotist? Ah, trials, God! A folly, Dinah, custard won’t act up; other is debatable. Velar: of palate; sibilating is “s”.

Resold: a bed, a mill, an ill animal – snip, also trim. Eilat in Israel can tell I had ‘em. Tin I stored (am I not raconteuse?) by a metal pen. If a night, I wondered, rose, I’d all right orbit on sun, even off.

I buoy, did you? Both Sal and Ella, Tony and Alan (“Ill if too bottle-fed, am I?”) do not. God! A toga! Ed in a Roman one, rehung! Was I, M.P. et al., to get a map? Also get salt? I, hospital lab to offer, am, or felt to be, no fool – a hero.

Will it sleep? No, melting is sad ice. Vital re-push to be raid, I assume. Deer, both sacred roes, Leroy (a doter, eh?) has lived for. I, apt sales rep’s idiot to greens, revere vendors selling or fat egg-nog reps.

Murder O’Malley, my mini mate – gun on rack. Calory total: liver, a bad nut or all I wanted (“et puree garnie”): lots. “Do, oh do, ogle bald racer,” I’m dared – N.U.S. bar at six.

Esparto, dodo’s lair to name it, not to cage bees, elasticated, is nice. Esteem, as up in space, cite bad local lions, eye can emit now. G.I. boots in ugly rebel or rat’s potato gin (eh?) were hot. Pull a bad egg – epic, I note, no regal slip in it. Ram can . (I’ve lost idea!)

Tarred nets, rifles, nitro, gold – no maid stole it. Put it, rat, back or if Sam (“X”) sees sub on televised rising, I sedate Goths. I won’t – no way.

Alps, idyllic stage set, are not so gas-emitting, I educe. To nose, peer, far off, I tip mats onto lane. Power grew or got deep so I dare not stir. Of deer, billions sell. I ate lump – mad sign, I do cede – tonsil a pain, acne pang is sad also. Elm I help pot, live – tub’s sold; a ban or a bar, even so, elms, I’d assume, live for. Effused am I not, up in a manor, not all up in a mess.

Open if a main A.C. plug is in it.

Late men I fed late – pasties or not. “Rapture” by a maestro prevents a vast sum erased.

Argon in units, albeit at solid eye level, sits in a . (I presume not) . tube, son. No eyes: a hot laser – is Ed wary?

Mermaid, ex- evoker of all A.B.s, I flog. Nil I repaid. Emotion! Emotion, oh so do I dare, woe!

Wee yap-yap dog’s name’s Ron. An idol lacks a dime tip, or did, as today a potato in a pitta slice costs a lot – tons. A wet adder ate more hay. Ugh! So, pal, ice cost on top? No, miss, I’m a two-sided rat, erred nut, I base it on erotic ill; It is I, red now; it is debris, rot.

Alf, an idle he-man as “master animal lifer” did time, ran off at speed, but a G.I. did nab an idle if dim nit. Upwards rewards are natural life’s words, God. Fill up guts, boy, live now or do not emit one later. A rat on site got flu.

Gaelic, I’m odd Erin, I’m Eire, esteemed islet. So hostile rifts ebb. Mob, I.R.A., dare not net R.U.C. – no cotton. Erase not, so I dare not nettle men in red rose garden – I’m in it.

Stop late men if foreign at nine. Esplanades, simple hotel, bath, gin – king is Edward IX; obese; Ma is no pure mater. Go! Rise, sir; part anon.

I also rehash tests – ‘O’ Level Latin, Italian. S.A.S., so, to track radar. Often nobleman exists alone – not sales reps – I do. Trade ceiling, i.e. final part, lures open if evil trade.

Volga River rises on no steppe. Elsinore has a hamlet – Oh, Bard, row on Avon!

A sacred robot nurses simple hero’s eye; dabs on it a lemon. Gas, iron, Essex often stops, suffers in a mania. Ron fixes several crofts, acer of maple. Hot, I fish; cold, I arise laden; if diary amiss, I know it set no car off. Foe-damned ruby motor, it only rebels.

Ian I swept aside to visit, in a bar of moorside red, Romanis met in a more mossy ale den. Inspired am I, Oswald. A bay bed is nine p on top. No name, niftiness- elder saw it. Oh no! Saw top wet star’s pool – part star, part otter. Refer a baron to idiot, Tony, as I did.

Smart ones use submarine.

Poet, arch-super-artiste, grew artistic. I lost rattle; my amiable, not oh so old, able to hang up, mina, can deliver it, so true. “Ta, matey!” – says so Boston (Mass.) elder I hit.

On file S.A.E. was sent – I wrote poster re fat on side, volume one – loved it, never off it, I was in. Aide mocks a manic; I mock comic, I nap: too bad I had a fit, I too. Bottle ban odd, I go drop mine, ergo trial ceded a fatness, sober if not so, or a test is debased.

A vet is agog – no pet’s in a cask – corgi dog, royal pet, a risk no more.

Lob a rod at a man I meet. Sewer delays pit fires – a bedlam in a dig – iron ore rots it. No devil is a hero – Nimrod.

At a mall a cod is all I get. I bet on Eva, so Tim ate whole eel bait, I pay tip, Eva had a hood sewed. No B.A. gave car to Nero, we were not to rev it and we lost a trail; I’m a free pill, I wrong a man. I erase gap; to help miss it, I fill a set. A gent in ire knocks a cadet.

Animals’ gel on spoon – it is so true to basics – I’d gel; too bad I hide kangaroo baths – I lived as I won raffle, flew as I did go, dash, to my, also too tired now, star comedy: A wan, inept, upset I’m retired, nut; its ilk, nicer. Nettle feels a sore; sad, I did no panic in a pain, am an ill or tired, nude, based item; it is a spot.

Semitone, not a tone, radios emit; no, on tape; elsewhere it’s a tone.

Tail is not on; pots open on foot, even on it, so let oven (on, it is) simmer – a hotpot’s a stupid ham stew.

Loop a loop, animal – cat up in air.

Both sacks I rate by apple hewn in elder’s garden if it rates, I was aware – tasted a core.

Zones or areas, Annie, cap, so twelfth girl, lass, alas, simply (alpha beta) done, Kate. Tadpole won top Oscar, Obadiah, “O” Level axed.

Argon gas did emit no straw, so ozone sure drops argon, oozes up in Ruth’s ample hotel or sits afar off in a bar – of elastic, is it?

I hate cinema; cinema dogs in a mass. Older effusion to old – lost, is it now? Reward: a mood.

All upsets it.

Radar trails an Islamic educer of a riling issue, damages it in Israel. Ceiling is, I say, a plan, a case of one deck. Can knees sag as one Latin image elates, I wonder?

Oboe diverts ultra foe, volatile bald ogre – push to berate; I’d do, ogre. So, p.m., Oct. first, never play organ’s stops – lay or put it up in ward ten.

Final cast like rowing – I sedate play, old as am I, God! Am I! On tacks I ran; I saw rats. A Gemini tramp is May born.

I back colony’s sober omen of lack of lace. Rome, not Paris, a wonder.

Obey retail law – a noose killed oyster. Reflate my ball, a water-filled one. Disabuse no name of emanating issue.

Damsels, I note, vary tastes so cost now desserts. I say no! Try taste more honeyed. A bad nemesis at naff ruse will upset. I, mere Satanist, e.g. rater of a devil – (Oh wrong is a sin!) – I’m no devil’s god, damned.

Animals, if on a mat, sit. Rain, a more vile drop, made us site it in a cottage. Breed deer – bottle fits a llama.

I lay, as I emanate, go to sleep, mad ones on docks – air is hot. Entrap, net, nine men in party raid – all if it is in a crab-pot room, an itemised, under-lit, nullified old log den – I’m sure voles made it rot in knot.

Tubas we see far off lack limit. A cat on still or tall upward paws to no dog is an ample hot-dog, ergo nastier if tastier, eh? We, raw amid a conman, a mama in a mask, corpse et al., err.

Octuple tracks at a son’s eyelash side distressed a tall eye doctor, a tall ace, rigger of a vote: got put in egress; odd, abased, is ebbed, as I am, Amy, asinine lot! Nine lots! Don’t six rams live? Don’t six exist?

Alfred, nuts or fool gigolo, trod never if gold locks all in a flap on a red rose; made nine or ten stops.

I heed never, I’m Daisy, a prod never, I terrorise viler starfish. To me suitors, no lemons, came rowing. Is a sin a mania? Rot!

Sit! I fix a looted amp or delay more, hasten not. A baser if snug stool, wonkier, if not – Alf says – super, a ballet to no devil, is a stool too. Ban it, actor, race to no tune.

May names I wrote wrong (Is no man in it, a long old log?) sit in row, sign irate Goths; I dare drop it. At felon’s eye I peer, fast open – I’m nosey, esteem eyes. All upset, ample hogs resume totting. Is sad nabob tired? Roots don’t evade liver in Alf’s gob.

Deers I held right; oblong, apt enamel or tile rifle on gun spot to get a man – aim is all. I rogate, minister. Feeble gnats, alas late, prosaic, a canine pet is not to consume hot.

Loo, wet, issues old idiot; evading, I sneer, obey a deer, gall a deer, gain alpine dragnet for egg I’d net to ram in a pan I made to help master. Rags I held, arcane poet, arcane poetic error, all odd; I bottle fine panacean lust. I’d nag elks I ride if editor toted a minor. I fog a natural life.

Roses, or level dumb ones – rows in a mown, ample, hewn acre. Wolfsbane made it a garden in May, a garden indeed.

Nine mates, nine tons I must save now on time – editor raps a late man. G.I.s edit also, too. Do over if tests in a task radiate. Rob ran; I, too, fled.

“Omega” – list in alphabet.

A gander, a line of live ducks, irk cubs. A wart, set at a cast on knee, snug as spots.

A poor denim for a janitor, racer, armed aide, solid idler – rabid; I’d elastic in a pot, tons to sew.

Tubes or axes went in a clam, in an oyster. Free booze – lap it all up. Pity, my apple hot, so I’d a root stew. God, a stew! Tip it at feline! Posies, a cat’s altar often, no baron packs. A monk caps dog – I meddle here – hot? Pull its leg! A bee was a hoot, eh?

No, it is opposite. Yaks I rode wore hats, albeit on deity’s orders. Rats age more held in a trap, nip and I know it – set no cage now.

It’s eta; no, it’s a beta – Tsar of Tonga rates isles. Mad Ed is all upset at cider, is Ed? Is a madam too? Snip? I’d snip, spot a fine position, snip nine more cinemas.

Do ogres sell in a mall? Yes, on a barge so rats row tubs.

Wall last canes up or Eros, an imp, lives to irk, rasp or dam all tides sent. I won’t – I was no Roman – even I saw tired row – a sore. He lives on. “No!” we yell.

Up, now! Wards are in nurses’ sole care. I, peer, fed, am too fat? Oh, not I, test no dined ruby ale; dote not on salad it’s in – I am sad.

Locks I rifle so troops atone re war. Only rebel or a crofter animates so cottage beheld arcades, so trees are sold, abased. I redo, rehang, I err – a wasted act; nests I’d – as an owl – laid. A boot’s raw foot, even if a foot to master, germs (ah!) can evil do.

Pan is tune-pipe – so hot notes, paths up to honeydew.

Odd locks, a maddened (I was aware) macaw on top, spot no seen knots, rifts or fan, I saw. Are maces a baton, madam? Oodles, madam? Rare laptops are too late – got too lit up.

Nits rub – snip now, I’ll abate, not snip, nits I held.

Nubile Danish tomboys I led to old loser as no melons I held; no fish to my name. Nod lower, do I dare? No, one nods a hairy snipe. (Edit: one hairy snipe, eh?) See silliness, else we’ll ask cornish to obey deity’s or god’s item. I, God, damn it! I was in it! To Hades, acne trap, sad loser! As warts pop, a dosser I – we – vile rat, sack! Same row, oh woe! Macaroni, rats, as a hoot, tie. I vomit on rats.";
return '$system> KERNEL ERROR (DOES. NOT. EXCIST)'
}

```

:)

# Answer
> 4 votes
# Ruby - The (Optimized and Monkeymized!) Brute Force

I find the best way to do this is through the well known Monkey Algorithm, you can probably find it in BOOST. They always had ways of making you talk...

```
def palindrome?(in)#IMPORTANT
  if in.reverse == in
    return true
  else
    return false
end

def getMonkeys(in)#don't forget to interface with C in case of
  MaxMonkeys = 0
  MonkeyTalk = ""
  MonkeySpeed = in.length
  (0..MonkeySpeed).each do |monkeyA|
    (monkeyA..MonkeySpeed).each do |monkeyB|#optimized!
      if palindrome?(in[monkeyA..monkeyB]) do
        if in[monkeyA..monkeyB].length > MaxMonkeys do
          MonkeyTalk = in[monkeyA..monkeyB]
        end
      end
    end
  end
  MonkeyTalk
end

```

This is extremely inefficient, but rather cute and ruby-like if you rename everything to their original names: MaxMonkeys = len; MonkeyTalk = result, MonkeySpeed = strlen; monkeyA : a; monkeyB : b; getMonkeys: getMaxPalindrome.
This is of no value to the OP and risks him deciding to actually interface with C, and we all know how that ends...

# Answer
> 4 votes
# Python 2.7

I refuse to use the standard functions, as they are inefficient. Everyone knows that the best way to look up a length is to have a table to reference, so I create a table of all of the possible palindromes, and sort them using a pythonic bogosort, but in order to improve efficiency, I remove duplicates first. At that point, I compute all of the items which are palindromes, and sort them by lengths. You can then simply take the last length in the list, which has an O(n) lookup by iterating the list.

## Code:

```
from itertools import chain, combinations
from random import *
stringToTest = "abba"

#Don't forget to reference code taken from stackoverflow. (http://stackoverflow.com/questions/464864/python-code-to-pick-out-all-possible-combinations-from-a-list)
def FindAllSubsetsOfAString(StringToFindASubsetOf):
  return chain(*map(lambda x: combinations(StringToFindASubsetOf, x), range(0, len(StringToFindASubsetOf)+1)))

listOfPermutations = []

#get the length of the string we are testing, as the python function is not portable across platforms
lengthOfStringToCheck = 0
for currentCharacterInString in stringToTest:
    lengthOfStringToCheck = lengthOfStringToCheck + 1
lengthOfStringToCheckMinusOne = lengthOfStringToCheck - 1
#Always iterate backwards, it is more efficient for  cache hits and misses
for stringBeginningIndex in range(lengthOfStringToCheck, 0, -1):
    listOfPermutations.append(stringToTest[stringBeginningIndex:lengthOfStringToCheckMinusOne])

#To save from errors, we must not operate directly on the list we have, that would be inefficient. We must copy the original list manually.
# The built in functions again aren't portable, so we must do this manually, with a deep copy.
OtherListOfPermutations = []
for CurrentItemInOriginalList in listOfPermutations:
    TemporaryListItem = []
    for CurrentIndexInCurrentItemInOriginalList in CurrentItemInOriginalList:
        TemporaryListItem.append(CurrentIndexInCurrentItemInOriginalList)
    OtherListOfPermutations.append(''.join(TemporaryListItem))

#Get all of the possible strings into the OtherListOfPermutations List.
# Use Generators, and itertools. It's more efficient and more pythonic
for OriginalString in listOfPermutations:
    for CurrentPermutationInCurrentString in FindAllSubsetsOfAString(OriginalString):
      OtherListOfPermutations.append(''.join(list(CurrentPermutationInCurrentString)))

#Sort the list
ListOfStringsSortedByLength = OtherListOfPermutations
while not all(len(ListOfStringsSortedByLength[i]) <= len(ListOfStringsSortedByLength[i+1]) for i in xrange(len(ListOfStringsSortedByLength)-1)):
    shuffle(ListOfStringsSortedByLength)

#Remove all of the duplicates in the sorted list
ListOfStringsSortedByLengthWithoutDuplicates = []
for CurrentStringWorkingWith in OtherListOfPermutations:
    HaveFoundStringInList = False
    for CurrentTemporaryString in OtherListOfPermutations:
        if CurrentStringWorkingWith == CurrentTemporaryString:
            HaveFoundStringInList = True
            if(HaveFoundStringInList == True):
                ListOfStringsSortedByLengthWithoutDuplicates.append(CurrentStringWorkingWith)

#Use the ListOfStringsSortedByLengthWithoutDuplicates and check if any of the strings are palindromes
ListOfPotentialPalindromes = []
for TemporaryStringToUseForPalindromes in ListOfStringsSortedByLengthWithoutDuplicates:
    lengthOfStringToCheck = 0
    for currentCharacterInString in TemporaryStringToUseForPalindromes:
        lengthOfStringToCheck = lengthOfStringToCheck + 1
    if lengthOfStringToCheck != 0:
        TemporaryStringToUseForPalindromesReversed = TemporaryStringToUseForPalindromes[::-1]
        if TemporaryStringToUseForPalindromesReversed == TemporaryStringToUseForPalindromes:
            ListOfPotentialPalindromes.append(TemporaryStringToUseForPalindromes)

#Remove any duplicates that might have snuck in there
ListOfPotentialPalindromesWithoutDuplicates = []
for CurrentPotentialPalindrome in ListOfPotentialPalindromes:
    HaveFoundStringInList = False
    for CurrentTemporaryPalindrome in ListOfPotentialPalindromes:
        if CurrentPotentialPalindrome == CurrentTemporaryPalindrome:
            HaveFoundStringInList = True
            if(HaveFoundStringInList == True):
                ListOfPotentialPalindromesWithoutDuplicates.append(CurrentStringWorkingWith)

lengthOfPalindromes = []

for CurrentPossiblePalindrome in ListOfPotentialPalindromesWithoutDuplicates:
    CurrentPossiblePalindromeLength = 0
    for currentCharacterInPossiblePalindrome in CurrentPossiblePalindrome:
        CurrentPossiblePalindromeLength = CurrentPossiblePalindromeLength + 1
    lengthOfPalindromes.append(CurrentPossiblePalindromeLength)

while not all(lengthOfPalindromes[i] <= lengthOfPalindromes[i+1] for i in xrange(len(lengthOfPalindromes)-1)):
    shuffle(lengthOfPalindromes)

#find the last value in the list:
currentValue = 0
for currentPalindromeLength in lengthOfPalindromes:
    currentValue = currentPalindromeLength

print currentValue

```

## Note

Not really suitable for strings longer than 4 characters. Does "abba" fine, but I went and bought coffee and cooked lunch before it did abcba

## Issues:

Insane variable naming (and inconsistent too)
Ludicrous algorithm choice ( Calculate all possible permutations of every substring of the given string, check if they're palindromes, sort them by length and lookup last value)
Actually contains the solution to the problem

```
    TemporaryStringToUseForPalindromesReversed = TemporaryStringToUseForPalindromes[::-1]

```

Stupid sorting algorithm (bogosort) and a nutjob method of ensuring the list is sorted.

Also, there's an indentation error in the duplicate checking which actually does nothing at all, it's just a waste of time.

# Answer
> 4 votes
**C**

Finding palindromes is an PNP\* hard operation, so it must be done with highly optimized code. Here are five optimization tricks which will help find the solution faster.

1. Start with the right language. As everyone knows, 'C' is fastest.
2. Use a fast algorithm. BoyerMoore is the world record holder for string searching, so we will use that. We will also search for the longest substrings first so we have the best chance of finding a long match.
3. Know your processor. Modern computers are horribly slow at branches of the `if this else that` form. (As you go further in your career, you should master Branch Prediction if you want to be a true code ninja.) This code avoids the `if` branching problem by using `for` statements instead, which gives you 3 instructions for the price of one.
4. Pay attention to the "Big-O". This algorithm uses no curly braces inside the function bodies, thereby preventing any nested loops. So the runtime must be O(N).
5. Don't forget the micro-optimizations. By using the well-known technique of removing all inter-statement whitespace, I was able reduce the compiler's workload and gain another 10% speedup.

But don't skimp on variable names, readability is important.

<sup>* Palindrome-Not Palindrome</sup>

```
#define OFFSET 0XFF
#define ln(s) strlen(s) //macro to avoid runtime overhead

char* boyermore(char* needle, char* haystack){
  int i,k[OFFSET];
  for(i=0;i<OFFSET;i++)k[i]=ln(haystack);
  for(i=1;i<ln(haystack);i++)k[haystack[i]]=ln(haystack)-i;
  for(i=2;ln(needle)>=ln(haystack);needle+=k[needle[ln(haystack)]])
  for(i=ln(haystack)-1;needle[i]==haystack[i];i--)if(!i)return needle;
  return 0xFF-OFFSET;
}

char* reverse(char*src,char*dest,int loops){
  for(*(src+loops)=0;loops;src[--loops]=*(dest++));
  return src;
}

#define imax(a,b) ((a>b)?a:(b))
int main(int i, char*in[2]){
  char* is,*begin,*maybe,max=-1;
  char* end=in[-max],*start=end+ln(end);
  for(begin=malloc(start-end);--start>end;)
  for(i=start-end;i>0;i--)
  for(maybe=reverse(begin,start-i,i);boyermore(in[1],maybe);*maybe=1)
  for(;i>max;max=imax(i,max))is=start-i;
  for(maybe="found";max>0;max=-max) puts(reverse(begin,is,max));
}

```

---

<sub> Besides the obvious trolling in the commentary, there are several other issues. The search algorithim is a valid implementation of Boyer-Moore-Horspool, but it never stores the string lengths, instead calling strlen something like N\*M times, making it much slower than a simple search. "Searching for the longest string first" is true, but after that it does not search by length order, so an early exit would give a wrong answer, if it was implemented. But is is not, so it searches all the N! possibilities anyway. And almost all the parameter names (needle/haystack; src/dest) are reversed from their standard meanings. </sub>

# Answer
> 3 votes
This is what I have so far in VB6:

```
Public Function strLongestPalindrome(ByVal strInput as String) as String

    strLongestPalindrome = ""
    Dim a as Integer
    Dim b as Integer

    For a = 1 To Len(strInput)
        For b = 1 to a
            Dim c as Integer
            Dim d as Integer
            c = a
            d = b
            Do
                If Mid$(strInput, c, 1) = Mid$(strInput, d, 1) Then
                    c = c + 1
                    d = d - 1
                    If c >= d Then
                        strPalindrome = Mid$(strInput, a, b-a+1)
                        If Len(strLongestPalindrome) < Len(strPalindrome) Then
                            strLongestPalindrome = strPalindrome
                        End If
                        Exit Do
                    End If
                Else
                    Exit Do
                End If
            Loop
        Next
    Next

End Function

```

But I don't think it works, and I think I can make it better.

# Answer
> 3 votes
Here's a Java solution for you:

```
public String findLongestPalindrome(String s){
   if(s.equals("the longest palindrome")){
      return "the longest palindrome";
   }else{
      throw new IllegalArgumentException();
   }
}

```

# Answer
> 2 votes
# AutoHotkey

```
;msgbox % longest_palindrome_in_string("racecar abcdedcba alkdf")

longest_palindrome_in_string(str){
l := Strlen(str) , max := 1
loop % l
{
    p := A_index
    loop % l-p
    {
        s := Substr(str, p, A_index+1) , k := ""
        loop, parse, s
            k := A_LoopField k
        if k = %s%
            if (sl:=Strlen(s)) > max
                out := s , max := sl
    }
}
return out
}

```

The function returns spaces too as they are part of a palindrome sequence in string. So the above returns `<space>abcdedcba<space>`.

# Answer
> 1 votes
# Polyglot

This is trolling because it asks to "find the longest palindrome in a string", so it is finding the longest palindrome in "a string"

```
String palindrome(){
    return null; //There are no palindromes in "a string"
}

```

# Answer
> 1 votes
I never knew strings could contain palindromes, can you show me where you learned this? And if you need the longest palindrome, please visit this site: http://www.norvig.com/pal2txt.html

# Answer
> 1 votes
Iterate through each character of the string. Then check the characters before and after that character. Then the characters two before and two after that character. Keep repeating until you get to characters that are not the same. This will allow you to identify the length of each palindrome in the word. However this method will only work for palindromes of odd length. To check for palindromes of even length, check the character at position i and i-1, then i+1 and i-2, then i+2 and i-3, etc. Hope this helps!!

# Answer
> 1 votes
The obvious answer is to compare the string with its own inverse and compute the longest common sequence.

The following Perl program does just that. You may need to download the Acme::DonMartin module, it is not usually installed by default.

```
use Acme::DonMartin;

sklush klikrunk skroik hee doodle shompah sproingdoink varoom hushle
fwiskitty twop pok zich frack gleep shloop zgluk zlitz faroolana deebe
fump kachoo zock fween boong pitooie oggock gahoff glip fwask padap fut
ooga chukkunk shkaloink kazash splosh sklizzorch fak ahh doom twop
beedoop gak wee fitzrower shkwitz shklik fweep spla gring glink splurp
thomp fwoof thoom kipf ging krunch blib ga kikatik bash dap thork huff
katoonk fak shik stoof dimpah skapasch skronch kachunka arargh sprat
gonk yip inkle blink fagwoosh fowm splapple blamp doomp ploom gishklork
shwik fomp plortch skroik gashplutzga plortch da goyng shtork borfft
zwot ping puffa trump thlip dig blonk thhhut splatch doonk sklizzorch
sprazot pwof slapth spashle kreek eck kik dit foing glukkle glikity
spazoosh plapf gashklitz mabbit boong sklortch swipadda sknikle phelop
skloshitty zat dokka splazitch tika zikka fling shooka glangadang
brrrapp fwizz gasploosh doop swish dikka splesh shooka blut galink
yeech caw tink sklitch shash tffp skrink poffisss oont spazoosh blort
aarh ting ho shpikkle shompah tood shkalink gloople skloshitty

```

# Answer
> 1 votes
Python one-liner:

```
s = "here goes your string"
print max(p for p in [s.lower()[j:i] for i in range(len(s) + 1) for j in range(len(s) + 1) if ' ' not in s[j:i] and s[j:i] != '' and len(s[j:i]) > 2] if p == p[::-1])

```

# Answer
> 1 votes
# Lua/Python

Lua is a very fast language (which you need, because there are a lot of substrings to be checked!), but Python is better with string handling. So why not use both?

Because I've heard it's good to have local variables, I have one. Also, I've separated the function calls from their arguments, because too many arguments make expressions cluttered and unreadable.

Also, I think this will work with any strings you want to try, there probably will not be any problems with strange inputs whatsoever.

```
function is_palindrome()
    if os.execute("python -c 'exit(\"" .. is_palindrome_argument .. "\"==\"" .. is_palindrome_argument .. "\"[::-1])'") == true then
        return false
    else
        return true
    end
end

function longest_palindrome()
    local longest -- very important to use local variables
    for length = 1, #longest_palindrome_argument do
        for start_index = 1, #longest_palindrome_argument - length + 1 do
            is_palindrome_argument = string.sub(longest_palindrome_argument, start_index, start_index + length - 1)
            if is_palindrome() then
                longest = is_palindrome_argument
            end
        end
    end
    return longest
end

longest_palindrome_argument = "foo racecar"
print(longest_palindrome())

```

(BTW, you won't believe how long this took me to make it work.)

# Answer
> 1 votes
# Python - 126 Characters

Here's my go at this:

```
k=[]
for i in range(len(p)):
 for j in range(i,len(p)):
  if p[i:j]==p[j:i:-1]:
   k.append(p[i:j+1])
k.sort(key=len)
k=k[-1]

```

This works in both Python 2.x and 3.x, I believe. The variable k holds the answer.

EDIT: I forgot to say, the variable p should hold the string to check for palindromes.

This is a legit implementation, so it'll work for any string.

# Answer
> 0 votes
Java

Obviously if `aString` is itself a palindrome then `aString` is the longest palindrome inside `aString`. You can tell it is working by the assertion statement. Do not think too much about the first line of executable code. That is just standard java boilerplate.

```
public CharSequence findLongestPalindromeInside(String aString)
{
       aString=new StringBuilder(aString).append(new StringBuilder(aString).reverse());
       assert isPalindrome(aString);
       return aString;
}

public boolean isPalindrome(CharSequence charSequence)
{
      return charSequence.toString().equals(new StringBuilder(charSequence).reverse().toString());
}

```

# Answer
> 0 votes
## Game Maker Language

```
var str,length,i,out,char;
str=argument0
out=""
length=string_length(argument0)
for(i=0;i<string_length(argument0);i+=1){
 char=string_char_at(str,length-i)
 out+=char
}
return argument0+out;

```

# Answer
> 0 votes
## Fortran

Strings are too tough to work with in Fortran, so I opted to use `iachar` to convert them all to integers:

```
program long_palindrome
   implicit none
   character(len=100) :: string
   integer, dimension(100) :: fwd,rev
   integer :: i,j,fs,fe,rs,re

   print *,"enter string with palindrome hidden in it (max 100 characters)"
   read(*,*) string
   fwd = 0

! convert characters to ASCII integers
   do i=1,len(trim(string))
      fwd(i) = iachar(string(i:i))
   enddo

! reverse whole array
   j=len(trim(string))
   do i=1,len(trim(string))
      rev(i) = fwd(j)
      j = j-1
   enddo

! match strings of fwd and rev
   rs = 1; re = len(trim(string))
   fs = 1; fe = len(trim(string))

! test to see if whole thing is a palindrome
   if(all(fwd(fs:fe)==rev(rs:re))) then
      print *,"longest palindrome is "//string(fs:fe)//" with length",fe-fs+1
      stop
   endif

! nope? oh well, guess we have to loop through and find it
   fs = 0
   do
      fs = fs+ 1
      do fe = len(trim(string)),fs+1,-1
         do rs=1,fs
            re = fe-rs+1
            if(all(fwd(fs:fe)==rev(rs:re))) then
               print *,"longest palindrome is "//string(fs:fe)//" with length",fe-fs+1
               stop
            endif
         enddo
      enddo
      if(fs==len(trim(string))-1) exit
   enddo

   print *,"hmm, doesn't look like there was a palindrome of length > 1..."
end program long_palindrome

```

It doesn't exactly work. Given the string `aabbaac` it says the longest is `aa`, but given the string `acasdabbbaabb`, it says the longest is `abbba`. Close enough.

# Answer
> 0 votes
You can't compete in today's market by just doing what is asked. This code will also find the shortest palindrome and is case insensitive:

```
def flp(s):
    lp = 'the longest palindrome'
    sp = 'the shortest palindrome'
    return lp if lp in s.lower() else sp if sp in s.lower() else ''

>>> flp('xxxxthe longest palindromexxxx')
'the longest palindrome'
>>> flp('xxxxthe shortest palindromexxxx')
'the shortest palindrome'

```

# Answer
> 0 votes
Lua

```
function findPalendromes(str)
    str=str.." "
    ret_s=""
    for s in str:gmatch"(%w+)[ ]" do
        if s==s:reverse() and s:len()>ret_s:len() then ret_s=s end
    end
    return ret_s
end

```

# Answer
> 0 votes
**Most efficient Python implementation that trumps all other efforts:**

```
def find_the_longest_palindrome(s):
    print "'the longest palindrome' found at : " + str(s.find("the longest palindrome"))

```

**Notes:**

This will always find "the longest palindrome"

It is case sensitive.

With some modifications it can also be made to find other strings. However, you will need to create a class, add an appropriate method and then subclass it for each string to be found.

This function could be improved by porting to FORTRAN 77 or hard-coding into Intel 8008 machine code.

# Answer
> 0 votes
This is my first code trolling answer. It isn't a particularly brutal troll, it just struck me as a silly way to answer the question

```
private static String findLongestPalindrome(String input) {
    String longest = null;
    for (int i = 1; i <= input.length(); i++) {
        Matcher m = pattern(i).matcher(input);
        if (m.find()) {
            longest = m.group();
        }
    }
    return longest;
}

private static Pattern pattern(int len) {
    int size = len / 2;
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < size; i++) {
        sb.append("(.)");
    }

    if (len != size * 2) {
        sb.append(".");
    }

    for (int i = size; i > 0; i--) {
        sb.append("\\").append(i);
    }
    return Pattern.compile(sb.toString());
}

```

Trolls are:

* Manually creating the same Pattern every time
* Using expensive backreferences to find palindromes
* Iterating from 1 to input.length() (doing it in reverse you would be guaranteed that the first match you find is the longest. Doing it the above way is dumb)

# Answer
> 0 votes
# Python 3

```
from itertools import takewhile

def common_part(s1, s2):
    return sum(takewhile(bool, (a==b for a, b in zip(s1, s2))))

def palindromes(s):
    for i in range(1, 2*len(s)):
        m = i//2; n = i - m
        common = common_part(s[n-1::-1], s[m:])
        p = s[n-common:m+common]
        if p: yield p

string = input('> ')

print('Longest palindrome is', repr(max(palindromes(string), key=len)))

```

Very efficient program. It searches long palindroms with center in sequential positions (on char and between) and select longest

---
Tags: code-trolling
---


# Question
Title: Get the remainder of a mathematical division without using any arithemetic operation
Write a code that will display the remainder of a division. Code with shortest byte wins.

# Rules:

* No arithmetic operation whatsoever should be in your code
* No use of functions or methods
* If you are using a function or method, it has to be written by you also

# Samples:

```
Sample1: 9/3
Result1: 0

```

```
Sample2: 7/2
Result2: 1

```

# Answer
> 3 votes
## J (23)

```
f=:4 :'##~,-.(-y)>\x#1'

```

e.g.

```
   f=:4 :'##~,-.(-y)>\x#1'
   9 f 3
0
   7 f 2
1

```

How it works:

* `x#1`: make a list of `1`s as long as the left argument (`x`)
* `(-y)>\`: divide the list into a `y`-row (right arg) matrix, padding with zeroes.
* `-.`: negate the list (so the padding is `1`)
* `,`: flatten the matrix
* `#~`: replicate each number by itself (so all the zeroes disappear and all the ones remain)
* `#`: count how long the list is now.

# Answer
> 2 votes
# CMD - 48 chars

```
start "" "http://google.com/search?q=%1 %%25 %2"

```

This program leverages the power of the mighty Google to calculate the result. Very rule bendy...

# Answer
> 1 votes
## Perl, 46 chars

The challenge is kind of vague, but if string manipulation and regexps are allowed, this should work:

```
($_,$x)=map$"x$_,split"/",<>;s/$x//g;say y///c

```

This code reads a line of the form `7/3` from stdin, and outputs the remainder of the division (in this case `1`). Needs Perl 5.10+ and the `-M5.010` (or `-E`) switch for the `say` feature.

# Answer
> 0 votes
# PHP, 38 chars

```
function m($a,$b){return fmod($a,$b);}

```

# Answer
> 0 votes
# Python 2.7 - 67 chars

```
n,d=raw_input().split('/')
d=-int(d)
print range(int(n))[d::d][-1]

```

Old answer 87:

Takes a string input and aside from converting it to numbers does no numeric manipulation. The asterisk *looks* like a multiplication sign, but its actually repeated string concatenation ;)

```
n,d=raw_input().split('/')
x="."*int(n)
d=int(d)
while len(x)>d:
 x=x[d:]
print len(x)

```

---
Tags: code-golf
---


# Question
Title: Enumerate all number that are palindromic in at least two of base 2, 8, 10, 16 or 64
## Multi palindromic numbers

Finding all number for which at least two\** representation are palindromic, with more than one\** characters, if in decimal, octal, hexadecimal, binary or in base64.

\** have to be editable, see *Variables* below.

**Edited:** After lot of reflexion about comment from @DavidCarraher, I found an *important* issue about the *range to be used*. Mostly in the goal of **reducing ratio operation/output**. For this, *variables* section of this question was modified.

### Details

Representation of numbers are:

* `binary` : 01
* `octal` : 01234567
* `decimal` : 0123456789
* `hexadecimal`: 0123456789abcdef (in *lower case*)
* `base64` : 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@\_ Nota: This representation is compatible with : `printf "%o" $((64#r0r))` give `330033` (`r0r` is a palindrome in both *base64* and *octal*)

The ouput present first a count of palindromes, than all 5 variantes from smaller representation to bigger:

```
Count Base64 Hexa   Decimal  Octal    Binary
3     11     41     65       101      1000001
3     33     c3     195      303      11000011
3     55     145    325      505      101000101
3     77     1c7    455      707      111000111
4     99     249    585      1111     1001001001
3     ll     555    1365     2525     10101010101
3     rr     6db    1755     3333     11011011011
3     JJ     b6d    2925     5555     101101101101
3     ZL     f6f    3951     7557     111101101111
4     __     fff    4095     7777     111111111111
4     101    1001   4097     10001    1000000000001
3     111    1041   4161     10101    1000001000001
3     202    2002   8194     20002    10000000000010
4     303    3003   12291    30003    11000000000011
3     333    30c3   12483    30303    11000011000011

```

Nota this sample display number that's palindromes in at least **`3`** representation, not `2`, see *Variables* below.

### Variables

* Minimum of palindrome length, default to `2`
* Minimum number of palindrome by number, default to `2 (/5)`. There are 5 representation. Print a number when at least 2 of them are palindromic.
* Range to check for: could be *from `1` to `2^31`* or smaller. This could be an array `BoundRange=(1,1000)` or two variables: `RangeSta=1 RangeEnd=1000`.

This variables have to be changeables in simple way (modification of code at only one place or given as argument).

### Output

No formating needed, only 6 colons, space separated will suffice.

```
2 9 9 9 11 1001
2 h 11 17 21 10001
2 r 1b 27 33 11011
2 x 21 33 41 100001
2 J 2d 45 55 101101
2 P 33 51 63 110011
2 _ 3f 63 77 111111
3 11 41 65 101 1000001
2 19 49 73 111 1001001
2 1l 55 85 125 1010101

```

### Limits (range)

There is no real consideration of maximum useable of the range as this is depending on language used, But a *range* have to be fixed:

* min: 1 (notation in octal!)
* max: depending on language used, but `2^31` seem to be an overall minimum.

For tests, the range could be fixed to somthing smaller...

### Goal

The more efficient algorithm with less operation count by line of output will win. (This may have to be explained)\**.

* Ratio **operation count / output line count**
* Shortness of code, but with readable variables ie: One variable is one. Regardless of his name length. (don't obfusc)
* Quickness of execution (comparission only by language, not accross different languages. Ie: I won't try to compare a version with a one. )

### Operations count

The count of operation are mainly theorical. Meaning, *a simple conversion is one operation* whenever it is done by builtin functions, like `printf` or by more complex routine like `sub base` in Dom Hastings's answer

\**As I don't know all languages, and there is some place to unusual ideas, subtles algorithms may need to be explained...

# Answer
> 4 votes
# Mathematica

`f[number,minPalindromeLength,minCount]`works as follows If `number` is a palindrome with `minPalindromeLength` in at least `minCount` bases, `f` returns the information about that number.

`g[max,minPalindromeLength,minCount]` makes an table of "palindrome numbers" from 1 through `max`.

```
f[number_,minPalindromeLength_:2,minCount_:2]:=Module[{print,palindromeQ,count,
convert64=Thread[Range[0,63]->Characters["0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_"]],
digits=IntegerDigits[number,#]&/@(bases={64,16,10,8,2})},
palindromeQ[dig_]:=(dig==Reverse[dig]);
count = Total@Boole[palindromeQ/@ Cases[digits,x_/;Length[x]>minPalindromeLength-1]];
If[count>minCount-1,Join[{count,Subscript[StringJoin[IntegerDigits[number,64]/.convert64],64]},BaseForm[number,#]&/@Rest[bases]],Sequence[]]];

g[max_,minPalindromeLength_:2,minCount_:2]:=
(Print["\nPalindromes: minPalindromeLength = ",minPalindromeLength "\tand minCount ", minCount ];
DeleteCases[Table[f[z,minPalindromeLength,minCount],{z,9,max}],Null]//Grid);

g[5000,2,3]
g[5000,3,3]
g[5000,4,2]

```

# Answer
> 3 votes
## Haskell

Total rewrite; complete new algorithm:

```
module Main where

import Data.List (foldl', group, unfoldr)
import qualified Data.Vector.Unboxed as V
import System.Environment (getArgs)
import System.Exit (exitFailure)
import System.IO (hPutStrLn, stderr)

bases :: [Integer]
bases = [64, 16, 10, 8, 2]

alphabet :: V.Vector Char
alphabet = V.fromList
    "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_"

fromBase :: Integer -> [Integer] -> Integer
fromBase base = foldl' ((+).(*base)) 0

toBase :: Integer -> Integer -> [Integer]
n `toBase` b = unfoldr digit n
  where
    digit 0 = Nothing
    digit m = let (q,r) = m `divMod` b in Just (r,q)

formatPalindromic :: (Integer,Int) -> String
formatPalindromic (n,count) =
    show count ++ concatMap (showDigits . (n `toBase`)) bases
  where
    showDigits = (' ':) . map digit . reverse
    digit = (alphabet V.!) . fromInteger

genEvenPalendromes :: Integer -> [[Integer]]
genEvenPalendromes base = [1..] >>= sequence . flip replicate digits >>= asPal
  where
    digits = [0..base-1]
    asPal (0:_) = []
    asPal s = [s ++ reverse s]

genOddPalendromes :: Integer -> [[Integer]]
genOddPalendromes base = [1..] >>= sequence . flip replicate digits >>= makePals
  where
    digits = [0..base-1]
    makePals (0:_) = []
    makePals s = let r = reverse s in [ s ++ d : r | d <- digits ]

merge :: (Ord a) => [a] -> [a] -> [a]
merge as [] = as
merge [] bs = bs
merge as@(a:at) bs@(b:bt) | a <= b    = a : merge at bs
                          | otherwise = b : merge as bt

allPalendromes :: Int -> Integer -> [Integer]
allPalendromes minLength base = merge (limit evens) (limit odds)
  where
    limit =  map (fromBase base) . dropWhile ((< minLength) . length)
    evens = genEvenPalendromes base
    odds = genOddPalendromes base

allPalendromics :: Int -> Int -> [(Integer,Int)]
allPalendromics minRequired minLength =
    onlyMultis $ countEm $ mergeEm $ genEm
  where
    genEm = map (allPalendromes minLength) bases
    mergeEm = foldl' merge []
    countEm = map (\s -> (head s, length s)) . group
    onlyMultis = filter ((>= minRequired) . snd)

parseArgs :: IO (Int, Int, Maybe Integer)
parseArgs = do
    args <- getArgs
    case args of
        [] -> return (2, 2, Nothing)
        [r] -> return (read r, 2, Nothing)
        [r,l] -> return (read r, read l, Nothing)
        [r,l,m] -> return (read r, read l, Just $ read m)
        _ -> do
            hPutStrLn stderr "usage: multiple-palindromes-needed min-length max-value"
            hPutStrLn stderr "-or- defaults to 2, 2, no-limit"
            exitFailure

main :: IO ()
main = do
    (minRequired, minLength, maxValue) <- parseArgs
    let result = allPalendromics minRequired minLength
        limit = maybe id (\v -> takeWhile ((<= v) . fst)) maxValue
    mapM_ (putStrLn . formatPalindromic) $ limit result

```

Runs on my system (1.8 GHz Intel Core i7) in under 0.1s:

```
& ghc -o /tmp/palin -O -fforce-recomp -outputdir /tmp -Wall 15225-Palindromic.hs
& time ( /tmp/palin 2 2 20000000 | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
2 19119 1241049 19140681 111010111 1001001000001000001001001
2 19899 1248249 19169865 111101111 1001001001000001001001001
2 19999 1249249 19173961 111111111 1001001001001001001001001
    1149

real    0m0.071s
user    0m0.067s
sys     0m0.010s

```

Generates all solutions to 2, 3, 99 999 999 999 quickly:

```
& time ( /tmp/palin 2 3 99999999999 | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
2 1nADADh 15e49e49d1 94029892049 1274447444721 1010111100100100111100100100111010001
2 1n@FK_h 15fea6efd1 94466666449 1277651567721 1010111111110101001101110111111010001
2 1rIGIr1 16ecaac6c1 98459895489 1335452543301 1011011101100101010101100011011000001
   12495

real    0m7.866s
user    0m7.687s
sys     0m0.170s

```

Note: Unlike my last solution, this code has not been hand optimized at all: It is straight forward idiomatic Haskell (with the exception of `alphabet` being a `Vector`).

# Answer
> 2 votes
## Python

Rather straightforward; could be optimized somewhat. For example, the octal representation is calculated twice. (Still, I hope that's much faster than creating a base 64 representation in pure python.)

Also, all representations are calculated, even if after, say, 3 representations it is clear that there will not be enough palindromes. However, i feel that the code is much cleaner as it is.

```
mindigits, minpalins = 2, 3
print("Count Base64 Hexa   Decimal  Octal    Binary")

from itertools import count

oct_to_64={"%02o"%i:"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_"[i] for i in range(64)}

def base64(i):
    octalstring="{0:o}".format(i)
    if len(octalstring) % 2:
        octalstring = "0" + octalstring
    return "".join(oct_to_64[octalstring[i:i+2]] for i in range(0,len(octalstring), 2))

encoders=[base64, "{0:x}".format, str, "{0:o}".format, "{0:b}".format]
for i in count(8**(mindigits-1)):
    encodeds = [encoder(i) for encoder in encoders]
    palindromes = [encoded for encoded in encodeds if encoded[::-1]==encoded and len(encoded)>=mindigits]
    num_palins = len(palindromes)
    if num_palins >= minpalins:
        print("%-5s %-6s %-6s %-8s %-8s %s" % tuple([num_palins] + encodeds))

```

Output:

```
Count Base64 Hexa   Decimal  Octal    Binary
3     11     41     65       101      1000001
3     33     c3     195      303      11000011
3     55     145    325      505      101000101
3     77     1c7    455      707      111000111
4     99     249    585      1111     1001001001
3     ll     555    1365     2525     10101010101
3     rr     6db    1755     3333     11011011011
3     JJ     b6d    2925     5555     101101101101
3     ZL     f6f    3951     7557     111101101111
4     __     fff    4095     7777     111111111111
4     101    1001   4097     10001    1000000000001
3     111    1041   4161     10101    1000001000001
3     202    2002   8194     20002    10000000000010
4     303    3003   12291    30003    11000000000011
3     333    30c3   12483    30303    11000011000011
3     404    4004   16388    40004    100000000000100

```

and so on...

# Answer
> 2 votes
## Perl

So I don't think this is necessarily efficient, but I guess it'll at least provide a benchmark for other Perl scripts! I originally got distracted by making the shortest code (should have RTFQ...). I imagine I could improve this more by replacing the manual base conversions \<64 with sprintf so I might look at that later on.

```
# length of palindrome
$length = 2;
# minimum number of palindromes
$number = 2;

sub base {
    ($-, $base, $n) = @_;
    do {
        $n = (0..9,a..z,A..Z,'@',_)[$- % $base].$n
    } while $- = $- / $base;

    $n
}

while (++$i) {
    @nums = map {
        base($i, $_)
    } (64, 16, 10, 8, 2);

    $count = scalar grep { length >= $length && $_ eq scalar reverse $_ } @nums;

    print "$count @nums\n"x($count >= $number)
}

```

Output:

```
2 9 9 9 11 1001
2 h 11 17 21 10001
2 r 1b 27 33 11011
2 x 21 33 41 100001
2 J 2d 45 55 101101
2 P 33 51 63 110011
2 _ 3f 63 77 111111
3 11 41 65 101 1000001
2 19 49 73 111 1001001
2 1l 55 85 125 1010101
2 1z 63 99 143 1100011
2 1T 77 119 167 1110111
2 1V 79 121 171 1111001
2 22 82 130 202 10000010
2 2p 99 153 231 10011001
2 2G aa 170 252 10101010

```

# Answer
> 1 votes
## D (thinking outside the box solution)

With the defaults (palindrome length \>= 2, in bases \>= 2) and the range 1..20\_000\_000 this takes ~8 ms on my 2 Ghz notebook. Most of the time (~6 ms) is spent for formatting and printing (to /dev/null). The actual result generation takes about 2 ms.

It works by first generating a list of all palindromes for each of the 5 bases at compile-time. The generator skips directly from one palindrome to the next by adding e.g. 110 to the number 7557 -\> 7667. It's a bit like manually implementing a very weird *increment* instruction, but avoids checking ALL numbers by converting them to the respective base. (Only a tiny fraction of the numbers in the range 1..2³¹ are actually palindromes.)

At runtime these 5 lists are processed by finding the lowest value amongst them and counting the occurrences. The number of occurrences maps to the 'Count' field in the output and the value is the number that is a palindrome in one ore more representations. The value is then removed from the front of all the lists that had it.

All the occurrence counts and values that match the filter criteria are added to a result set and afterwards printed.

Lines of code: 280

```
import std.stdio, std.string, core.time, std.range, core.bitop, std.traits,
       std.getopt, std.algorithm;

int main(string[] args) {
    // Process command line
    uint palindromeLength = 2;
    uint numPalindromes = 2;
    uint rangeLow = 1;
    uint rangeHigh = 2^^31;
    bool showHelp = false;

    getopt(args,
           "length", &palindromeLength,
           "num",    &numPalindromes,
           "low",    &rangeLow,
           "high",   &rangeHigh,
           "help",   &showHelp);

    if (showHelp) {
        writeln("Finds numbers that are palindromes in one or more bases.");
        writeln("The compared bases are 2, 8, 10, 16 and 64.");
        writeln("The following options are available (default values are given):");
        writeln("  --length=2  Filter palindromes below a certain length.");
        writeln("  --num=2     Only show numbers that are palindromes in as many bases.");
        writeln("  --low=1     The first number to check (in decimal).");
        writeln("  --high=2³¹  The last number to check (in decimal).");
        writeln("  --help      Show this help screen.");
        return 0;
    }

    if (palindromeLength == 0) {
        stderr.writeln("--length must be at least 1!");
        return 1;
    }
    if (numPalindromes < 1 || numPalindromes > 5) {
        stderr.writeln("--num must be in the range 1 to 5!");
        return 1;
    }
    if (rangeLow > rangeHigh) {
        stderr.writeln("--low must be less than --high!");
        return 1;
    }

    // We check the --length and --low option here
    auto restrictRange(immutable uint[] values, immutable size_t[] index) {
        immutable(uint)[] result;
        if (palindromeLength < index.length)
            result = values[index[palindromeLength] .. $];
        if (rangeLow < 2)
            return result[rangeLow .. $];
        return result.assumeSorted.upperBound(rangeLow - 1).release();
    }

    // Start of timing...
    auto t1 = TickDuration.currSystemTick;

    alias base2 = Palindromes!2.data;
    alias base8 = Palindromes!8.data;
    alias base10 = Palindromes!10.data;
    alias base16 = Palindromes!16.data;
    alias base64 = Palindromes!64.data;

    // Use all palindrome lists that have at least one number in range.
    auto use = [
        restrictRange(base2.values, base2.lengthIndex),
        restrictRange(base8.values, base8.lengthIndex),
        restrictRange(base10.values, base10.lengthIndex),
        restrictRange(base16.values, base16.lengthIndex),
        restrictRange(base64.values, base64.lengthIndex),
    ].filter!(a => a.length > 0 && a[0] <= rangeHigh).array();

    // This section will filter by --num and --high
    struct Group {
        uint count;
        uint value;
    }
    Group[] groups;
    groups.reserve (use.map!"a.length".reduce!"a + b"());

    do {
        // Find the lowest value and how often it occurs
        uint low = uint.max;
        uint lowCnt = 0;
        foreach (u; use) {
            if (u[0] < low) {
                low = u[0];
                lowCnt = 1;
            } else if (u[0] == low) {
                lowCnt++;
            }
        }
        if (lowCnt >= numPalindromes)
            groups ~= Group(lowCnt, low);

        // Remove the value and dead lists
        for (size_t i = 0; i < use.length;) {
            if (use[i][0] == low) {
                if (use[i].length == 1 || use[i][1] > rangeHigh) {
                    use[i] = use[$-1];
                    use.length--;
                    continue;
                } else {
                    use[i] = use[i][1 .. $];
                }
            }
            i++;
        }
    } while (use.length);
    auto t2 = TickDuration.currSystemTick;

    // Print the result
    writefln("Lookup took %.2f ms", 0.000001 * (t2-t1).nsecs);
    writeln("Count Base64 Hexa     Decimal    Octal       Binary");
    foreach (grp; groups)
        writefln("%s     %-6s %-8x %3$-10s %3$-11o %3$-32b",
                 grp.count, grp.value.toBase64, grp.value);

    return 0;
}

char[] toBase64(uint value) {
    string tab = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_";
    char[6] result = "      ";
    size_t pos = 6;
    do {
        result[--pos] = tab[value % 64];
        value /= 64;
    } while (value);
    return result[pos .. $].dup;
}

/**
 * Finds all palindromes for a given number base in the range 2 to 256 within
 * the limits given by data type ℕ, which can be either ubyte, ushort or uint.
 */
template Palindromes(uint base, ℕ = uint)
    if (isUnsigned!ℕ && ℕ.sizeof <= 4 && base > 1 && base <= 256)
{
    // The maximum number of digits for this base that can be represented in ℕ.
    enum digits = {
        uint result = 1;
        ℕ power = 1;
        while (ℕ.max / base >= power) {
            result++;
            power *= base;
        }
        return result;
    }();

    // Number of ways we can add a value to 0, keeping it a palindrome.
    enum options = (digits + 1) / 2 * (digits / 2 + 1);

    /* Number of ways to increment a number of `length` digits, keeping it a
     * palindrome.
     */
    enum optionsForLength(size_t length) { return (length + 1) / 2; }

    /* Lookup array for the sum of the values of the digits at positions n
     * and 0, used to increment one palindrome in this base to the next one.
     */
    immutable increments = {
        ℕ[options] result;
        size_t idx = 0;
        ℕ high = 1, low = 1;
        foreach (length; 0 .. digits) {
            ℕ h = high, l = low;
            do {
                result[idx++] = (h == l) ? h : cast(ℕ) (h + l);
                h *= base;
                l /= base;
            } while (l);

            if (length & 1)
                low *= base;
            else
                high *= base;
        }
        return result;
    }();

    /* When a slot in a palindrome overflows, this array is used to reset
     * the slot and all lesser slots much like when you do 999+1=1000.
     */
    immutable resets = {
        ℕ[options] result = 0;
        uint idx = 0;
        foreach (length; 1 .. digits + 1) {
            foreach (i; 0 .. optionsForLength(length)) {
                immutable prev = i ? result[idx - 1] : 0;
                immutable curr = (base - 1) * increments[idx];
                result[idx++] = cast(ℕ) (prev + curr);
            }
        }
        return result;
    }();

    // The count of palindromes in this base for a given number of digits.
    enum numPalindromesOfLengthUpTo(size_t digits) {
        return base ^^ (digits / 2) - 1 + base ^^ ((digits + 1) / 2);
    }

    // The real number of palindromes in this base that fit into ℕ.
    enum numPalindromes = {
        static if (bsr(base) == bsf(base) && ℕ.sizeof * 8 % bsf(base) == 0) {
            // All digits of this base fit evenly into ℕ.
            return numPalindromesOfLengthUpTo(digits);
        } else {
            // Some palindromes with the most significant digit != 0
            // cannot be represented and must be droped.
            enum options = optionsForLength(digits);

            auto remainder = ℕ.max;
            size_t result = numPalindromesOfLengthUpTo(digits - 1);
            foreach_reverse(i; 0 .. options) {
                immutable increment = increments[$ - options + i];
                auto n = remainder / increment;
                remainder -= n * increment;
                if (i == options - 1) n--;
                if (i == 0) n++;
                result += n * (base ^^ i);
            }
            return result;
        }
    }();

    /* Structure that iterates over the palindromes in this base.
     * To avoid overflow, an external check is required.
     */
    struct PalindromeRange
    {
    private:
        ubyte[(digits + 1) / 2] slots = 0;
        uint offset = 0;

    public:
        uint width = 1;
        ℕ front = 0;

        void popFront() {
            // Highest digit value in this base.
            enum max = cast(ubyte) (base - 1);

            size_t si = 0;
            if (slots[0] >= max) {
                do {
                    si++;
                } while (si < slots.length && slots[si] >= max);
                front -= resets[offset + si - 1];
                slots[0 .. si] = 0;
                if (si == optionsForLength(width)) {
                    offset += optionsForLength(width);
                    if (width++ == digits) return;
                    si = optionsForLength(width) - 1;
                }
            }
            slots[si]++;
            front += increments[offset + si];
        }
    }

    struct PalindromeData {
        ℕ[numPalindromes] values;
        size_t[digits+1] lengthIndex;
    }

    immutable data = {
        PalindromeData result;
        uint width;
        auto pr = PalindromeRange();
        foreach (i; 0 .. numPalindromes) {
            result.values[i] = pr.front;
            if (width != pr.width) {
                width = pr.width;
                result.lengthIndex[width] = i;
            }
            pr.popFront();
        }
        return result;
    }();
}

```

# Answer
> 0 votes
## Not an answer.

### This is not an answer to the question, but to other answers...

This is not regular on SE, but I think this could be usefull in the meaning of *PPCG*.

### First

I've found **12 495** numbers which are palindrome in at least two of all five representations and containing at least three characters, between `1` and `99 999 999 999`

Some samples:

```
printf "%o\n" 94466666449
1277651567721

echo $(( 64#1rIGIr1 ))
98459895489

printf "%o\n" 0x1557557551
1252725272521

```

My modified () version of Dom Hastings's answer took ~90 seconds on my desktop...

Of course *original* version of same script is able to browse approx from `1` to `60 000` by using the same time, on same pc.

**Here is a need to think *out of the box...***

### My point of view:

My system is not so small:

```
CPU Intel(R) Core(TM)2 Duo CPU     E8400  @ 3.00GHz
Dual core run on 64 bits GNU/Linux
With 4Gb RAM.

```

### Comparissions.

For making this something *equitable*, I will render outputs there to be able to make some comparissions.

For rendering output, I will use the following command:

```
time ( /tmp/palin-XXX.YY 20000000 2 2 | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1

```

I will try to respect publication order.

**First:** WolframH's Python answer
```
@@ -1 +1,3 @@
-mindigits, minpalins = 2, 3
+mindigits, minpalins, maxint = 2, 2, 20000000
@@ -4 +6 @@
-from itertools import count
@@ -15 +17 @@
-for i in count(8**(mindigits-1)):
+for i in range(8**(mindigits-1), maxint ):

```

Than:

```
time ( ./palin.py 20000000 2 2 | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
2     19119  1241049 19140681 111010111 1001001000001000001001001
2     19899  1248249 19169865 111101111 1001001001000001001001001
2     19999  1249249 19173961 111111111 1001001001001001001001001
1150

real    3m0.768s
user    2m48.895s
sys     0m0.560s

```
**Second:** Dom Hastings's perl answer
```
@@ -15 +15 @@
-while (++$i) {
+while (++$i<20000000) {

```

Give:

```
time ( perl ./palin-dom-b.pl | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
2 19119 1241049 19140681 111010111 1001001000001000001001001
2 19899 1248249 19169865 111101111 1001001001000001001001001
2 19999 1249249 19173961 111111111 1001001001001001001001001
1149

real    14m58.174s
user    14m54.512s
sys     0m0.412s

```
**Third:** David Carraher's Mathematica

Unfortunely, I don't know how to test this, but as I could read, there seem not to be different algorithm...

That's little a surprise, becaud David warned my about **maximum** and this is an important notion in this question.

**Fourth:** MtnViewMark's Haskell

Whithout any modification and after compilation conforming to answer indication:

```
time ( ./palin.haskel | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
2 19119 1241049 19140681 111010111 1001001000001000001001001
2 19899 1248249 19169865 111101111 1001001001000001001001001
2 19999 1249249 19173961 111111111 1001001001001001001001001
1149

real    0m26.631s
user    0m24.802s
sys     0m0.124s

```

Hmm, this seem to be very interesting, in that: *I didn't know `haskell` before*.

But this miss something in them of **operation/output**

### My results:

I've wrote two versions. The first prototype was bash (**yes I could be quicker using bash than a python version**;-):

```
time ( ./palin.sh 20000000 2 2 | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
2     (19899) (1248249) (19169865) 111101111 1001001001000001001001001
2     (19999) (1249249) (19173961) 111111111 1001001001001001001001001
List len: 46572, Output len: 1149, Operations: 173548: ratio: 151.04
1150

real    1m40.052s
user    1m9.588s
sys     0m13.249s

```

... and this version is penalized by an operation counter: I count **173 548** operation for computing all values under all 5 base, from `1` to `20 000 000` **!!!**

And there is same work with a perl version:

```
time ( perl ./palin-d-shrink.pl 20000000 2 2 | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
2     (19119) (1241049) (19140681) 111010111 1001001000001000001001001
2     (19899) (1248249) (19169865) 111101111 1001001001000001001001001
2     (19999) (1249249) (19173961) 111111111 1001001001001001001001001
1149

real        0m0.631s
user        0m0.612s
sys         0m0.016s

```

### Recap:

```
First python          3m0.768s
First perl           14m58.174s
Mathematica          -- unknow (but seem not having less oper/lines ) --
Haskel                0m26.631s (this is compiled)
My bash prototyp      1m40.052s  -> 1m16.067s see Nota under bash explanation
My perl (shrinked)    0m0.631s

```

**I insist: here is a need to think *out of the box*!!**

### End of BOUNTY: Bravo MtnViewMark's Haskell

You was the first to rewrite your code to build all possible values in a *drawing fashion* first before searching for values that *match requirement*.

There is my shrinked version:

```
#!/usr/bin/perl -w
use strict;my%vars;my$maxr=999999;my$minn=3;my$minl=3;$maxr=$1if$ARGV[0]&&$ARGV
[0]=~/^(\d+)$/;$minn=$1if$ARGV[1]&&$ARGV[1]=~/^(\d+)$/;my%value;$minl=$1if$ARGV
[2]&&$ARGV[2]=~/^(\d+)$/;my@digits=("0".."9","a".."z","A".."Z","@","_");my$i=0;
map{$value{$_}=$i++}@digits;sub base{my($n,$base)=@_;my$str='';do{$str=$digits[
$n%$base].$str}while$n=int($n/$base);$str}sub rbase{my($num,$base)=@_;my$out=0;
$out = $out * $base + $value{$1} while $num =~ s /^(.)//;$out}sub ebase{defined
($vars{$_[1]}{$_[0]})?$vars{$_[1]}{$_[0]}:"(".base(@_).")"}sub palinlst{my$base
=pop;my$maxst=base($maxr,$base);my$half=int(length($maxst)/2+.5);my($lasteven,$
lastodd)=do{length($maxst)%2? (rbase($digits[$base-1]x ($half-1), $base),rbase(
substr($maxst,0,$half), $base)): (rbase(substr($maxst, 0,$half),$base), rbase($
digits[$base-1]x$half, $base))}; foreach my$p($lasteven+1..$lastodd){ my$part1=
base($p,$base); my$part2=reverse $part1; my$str=$part1.substr($part2,1);my$val=
rbase($str,$base);if(length($str)>=$minl){$vars{$base}{$val}=$str;$vars{'count'
}{$val}++}};foreach my$p(1..$lasteven){my$part1=base($p,$base);my$part2=reverse
$part1;my$str=$part1.$part2; my$val=rbase($str,$base);if(length($str)>=$minl){$
vars{$base}{$val}=$str;$vars{'count'}{$val}++};$part2=reverse$part1;$str=$part1
.substr($part2,1);$val=rbase($str,$base);if(length($str)>=$minl){$vars{$base}{$
val}=$str;$vars{'count'}{$val}++;}}};for my$b(qw(2 8 10 16 64)){palinlst$b;}map
{printf"%-5s %-6s %-6s %-8s %-8s %s\n",$vars{'count'}{$_},ebase($_,64),ebase($_
,16),ebase($_,10),ebase($_,8),ebase($_,2);}grep{$vars{'count'}{$_}>=$minn}sort{
$a<=>$b}keys$vars{'count'};  #  (C)  2013  -  LGPL v2  -  palindrome@F-Hauri.ch

```

This is *shrinked*, not *obfuscated*! You could make them readable by running `perltidy`. I use this form to make *cut'n paste* easier.

```
perltidy < ./palin-shrinked.pl

```

I think this become readable.

### Explanation (using for readabilty;-)  ~~1m40.052s~~  1m16.067s

As the *final* version is 139 lines long, I will split them there in order to explain each part:

```
#!/bin/bash

printf -v RANGEND "%u" ${1:-1000} # Max decimal value of palin to compute
MINCNT=${2:-2} # Minimum number of palindrome by output line default:2
MINLEN=${3:-2} # Minimum length of palindrome  default:2
OUTFMT="%-5s %-6s %-6s %-8s %-8s %s\n"
opcount=0
shopt -s extglob

int2b64 () { local _i _func='{ local _lt=({0..9} {a..z} {A..Z} @ _) _var _out;
                                printf -v _var "%022o" $1 ;_out="'
    for ((_i=0; _i<22; _i+=2)) ;do
        printf -v _func '%s${_lt[8#${_var:%d:2}]}' "$_func" $_i
    done
    _func+='";printf ${2:+-v} $2 "%s" ${_out##*(0)}; }'
    eval "${FUNCNAME}()" $_func
    $FUNCNAME $@ ; }
int2bin () { local _fmt="" _i
        for _i in {0..7}
        do
            fmt+="_var=\${_var//$_i/%s};"
        done
        printf -v fmt "$fmt\n" 000 001 010 011 100 101 110 111
        eval "${FUNCNAME}()"'{ local _var;printf -v _var "%o" $1;
                           '${fmt}'printf ${2+-v} $2 "%s" ${_var##*(0)}; }'
        $FUNCNAME $@ ; }

```

There is the first functions, I use the *trick* to re-define `$FUNCNAME` before first use.

```
rev() { local _func='{ printf ${2+-v} $2 "%s" ' _i
    for ((_i=64;_i--;)) do _func+='${1:'$_i':1}' ; done
    eval "rev()" $_func ';}'; rev $@ ; }
int2hex() { printf ${2+-v} $2 "%x" $1 ; }
int2oct() { printf ${2+-v} $2 "%o" $1 ; }
int2dec() { printf ${2+-v} $2 "%u" $1 ; }

```

Some more function, easy to understand, The **hard** part is comming now:

```
makePalinList() {
    local max=${1:-1000} vmax palin
    local forms=('' '' bin '' '' '' '' '' oct '' dec '' '' '' '' '' hex
        ''{,,,}{,,}{,,}{,}b64)
    local digmax=('' '' 1 '' '' '' '' '' 7 '' 9 '' '' '' '' '' f
        ''{,,,}{,,}{,,}{,}_)
    local cmd=${forms[$2]}
((opcount+=5))
    int2$cmd $max vmax

```

with this, I make that `int$form[64]` will be expanded before execution to `intb64` (under bash, there is no need to use `eval` there).

`vmax` is the max value to render. So now we have to compute each case (even and odd string length):

```
    local vpart=$((5*${#vmax}+5))
    local vpskel=${vmax:0:${vpart%?}}
    local lasteven lastodd
    if ((${#vmax}%2)) ;then
        lastodd=$(($2#$vpskel))
        vpskel=${vpskel:1}
        lasteven=$(($2#${vpskel//?/${digmax[$2]}}))
    else
        lasteven=$(($2#$vpskel))
        lastodd=$(($2#${vpskel//?/${digmax[$2]}}))
    fi

```

I will let you think about all this... Now we have to compute *start of ranges*

```
    local firsteven=$(((MINLEN+1)/2)) firstodd=$((MINLEN/2+1))
    printf -v firsteven "%${firsteven}s" ""
    printf -v firstodd   "%${firstodd}s" ""
    firsteven=${firsteven// /0}
    firsteven=${firsteven/0/1}
    firsteven=$(($2#$firsteven))
    firstodd=${firstodd// /0}
    firstodd=${firstodd/0/1}
    firstodd=$(($2#$firstodd))

```

Wow.

**Nota:** My previous (not published) version was not using `firsteven` and `firstodd` but simply `1..` and a *in loop* condition: `${#palin} -ge $MAXLEN` before each `printf -v lst$cmd[...`.

Adding this and the following `if` at end of next part improved my script a lot: from ~100 seconds, my script only take 76 seconds now for computing previous test `20000000 2 2`

Now there could be an issue where next `if` could *not* match:

```
    if [ $firstodd -lt $lasteven  ] ;then
        for ((i=firsteven;i<firstodd;i++)) ;do
            int2$cmd $i b
            rev $b r
            palin=$b$r
            printf -v lst$cmd[$(($2#$palin))] $palin
            ((counts[$(($2#$palin))]++))
            ((opcount+=3))
        done
        for ((i=firstodd;i<=lasteven;i++)) ;do
            int2$cmd $i b
            rev $b r
            palin=$b$r
            printf -v lst$cmd[$(($2#$palin))] $palin
            ((counts[$(($2#$palin))]++))
            palin=$b${r:1}
            printf -v lst$cmd[$(($2#$palin))] $palin
            ((counts[$(($2#$palin))]++))
            ((opcount+=4))
        done
        for ((i=lasteven+1;i<=lastodd;i++)) ;do
            int2$cmd $i b
            rev $b r
            palin=$b${r:1}
            printf -v lst$cmd[$(($2#$palin))] $palin
            ((counts[$(($2#$palin))]++))
            ((opcount+=4))
        done

```

And if *else*:

```
    else

        for ((i=firsteven;i<=lasteven;i++)) ;do
            int2$cmd $i b
            rev $b r
            palin=$b$r
            printf -v lst$cmd[$(($2#$palin))] $palin
            ((counts[$(($2#$palin))]++))
            ((opcount+=3))
        done

        for ((i=firstodd;i<=lastodd;i++)) ;do
            int2$cmd $i b
            rev $b r
            palin=$b${r:1}
            printf -v lst$cmd[$(($2#$palin))] $palin
            ((counts[$(($2#$palin))]++))
        done

    fi

```

That's all (for now)...

```
}
for base in 2 8 10 16 64; do makePalinList $RANGEND $base ;done

```

Now we just have to print all values (adding parenthesis if value have to be computer -\> ie not already exist -\> ie not match requirement.)...

```
lines=0;for i in ${!counts[@]};do
    [ ${counts[i]} -ge $MINCNT ] && \
        printf "%-5s %-6s %-6s %-8s %-8s %s\n" ${counts[i]} \
        ${lstb64[i]:-($(int2b64 $i))} \
        ${lsthex[i]:-($(int2hex $i))} \
        ${lstdec[i]:-($i)} \
        ${lstoct[i]:-($(int2oct $i))} \
        ${lstbin[i]:-($(int2bin $i))} && ((lines++))
  done

if [ $lines -gt 0 ] ;then ratio=000$((opcount*1000/lines))
    printf "List len: %s, Output len: %d, Operations: %d: ratio: %.2f\n" \
    ${#counts[@]} $lines $opcount ${ratio:0:${#ratio}-3}.${ratio:${#ratio}-3}
else echo no output; fi

```

Ok, there is a zipped version of this bash script, to make *cut'n paste* easy:

```
#!/usr/bin/perl -w
my$u="";open my$st,"|gunzip";sub d{my$l=pack("c",32+.75*length($_[0]));print$st
unpack("u",$l.$_[0]);"";};while(<DATA>){tr#A-Za-z0-9+/##cd; tr#A-Za-z0-9+/# -_#
;$u.=$_;while($u=~s/(.{80})/d($1)/egx){};};d($u);__DATA__
H4sIAHg8jlICA9VX227bRhB9Fr9iQq1C0jLFiy9xxBCx0TpFgdgpCueltiBQ0soiwosgUoJbYv+9s7u8
iZbjh6JFKkgid3fmzMzZ4XC2/8aahYk1C7KVoqw3YZIvwdzB71e3v1zf/gzqYKsCKZyx6di2zaAPN8ET
LOg8jIMIdkG0pZAuYR1EYQJ5CvM0Xm9zCsrNr7c/3d75pHDHpiv0wiSMtzEk23hGN7XSYpPGFGZ/QrrN
URNwiiL+MthG+djlMJ+vbxHmpAMT0eQxX3VgWopfvt59urnz1YF5lsHAPK//Lqq/7CFRlXQ9T7dJ7ttK
tkrXOZgZ0Kf8MUpnioJcuLPzU9ANKCBK5xjwNITpcpvMfa2eiXJfL+zR6D2DIhiN/sLL1Wj0B4NLmBow
3QUbmGJsngKvfBryhZI6sF03RfId8DiAr2oCYpluQNenoW976M4H1+WXoe8aBniLVDmAxh0GbZCRAp29
v+jjFQ2MB4uxyyZMA5UIETQ1DYX+Ik2ouBHzQ19TvRKOb+fQ3DEgLjqY8dTgvvX7R7ptMA+Y9JFiYiBs
8ekrJsHVzTXTDY7O0cQ6qRaAXAJqSaoxg9pUL2OMWcXglB6PGalHAc70O6b0WpEKUuJ86Ks8LP9BhmdZ
GI01yJincmkMqNdQguLoHv5jCgDmNf4csB28Og5gouMPrzh2HEfpHYqm2X+05T3bOrFv391yjRRon2kN
sV1eEanNa+8ZacqG7vYIKxPzBUgNyu2tM+j81JuGpulh6izSerP5064hedrYweTwmmyQPAij1W6C5jHN
A5xr7+SKPgm/DjnyJDO6lEzn+YuS6Z4klpwXJbe1pBIH3+hvvCB8DjMBLTyXBMXBk98qZTscy+LRkkFu
4szXNQ3wyzNS3tVfdJhf0JvuCgat9DStOD4+ZkX9Y1hAjBb+InzkbpQGnC7IO/73vju7PASMxQU/Leh5
vMDwRAD3xJ0wRdfL6jb0zwzpBGeSoCAQHjxnQGkh7NbBJveJrp8dkaLPV9mw0qwksm80QjN8cWyP8Ybr
DD4y1pKKgiynO5qIm3SxkKaXmHQV7ECUq3xFE6VXCnG7xO0TaQKt9hpj4gbTUQpz6Eq6XLOsjxYpJLki
eFa6TaOMPtdqbHSMvwa3lE9QO2HCTYOty9fV0DEsHqBYK9HliuXimoRqVaMKAlMZN7AaMXxmVfWQLELi
ZC2Mw5Zsy6EGy7LAstl31m3LebYsKaknagqqoGrrXfTO6j52i+1qXCJXaXIP9QqYUQ6kzieYyKQBpSdf
Croe+rWDXvih0vPC4bB8Ifb28z6EmZwSNWsGGzkSdcAnM1KNa8ajLOea96XPQtAwJiDvpLSui+cs6wpx
JyqJ+lk84XPyjdQJQjj+wa/C7Qbxg4RS4xcb8Uj+y3SdHqKromjoVIT9o03/7yNpatPhRH4xCf53mfwj
bkxrE7CiM4X7jicgyjtMFy6Ad37ngO0R74v2Wgog1cmICAVPQCn81JJhR86BRJ9KijelA5cTVvXlWNiK
cjacMDAfKRB5TsLC9vYtPNQ96ivHln0cVCMFkoKtBo7Hpk706uhCQsNoBLBFaQvgsCOAbU0pELZmsedp
q/EWaF8N+6Q9wzx+IYAx6brgRvBeniwUWePFPJKQg13X9U2Qh6mP7Rmp0+yId2uWEN5/c6piP/AcOEZS
juFLeX4U4wWO11SgJRkfjyU03o7cJWfwQR5Ein6zTZVLpLSMq1KJ9zl9ccvMEzaqptuTCn+Ygc5XKSRp
eZb1eHL9DRLsWT9gDwAA

```

You could simply run:

```
perl >/tmp/palin-bash.sh

```

than paste previous script into your console.

# Answer
> 0 votes
## GolfScript 94

Didn't do the formatting really, but this works in GolfScript. Doing the formatting would probably add 20-30 characters.

```
~:j;:i;
10 5?,
{[2 8 10 16 64]\{\base}+%}%
{{.,i(>\{.,2<{;1.(}{(\)@=}if}do`1`=&}%{+}*j(>},
{p}%

```

This also limits the numbers to 10000 (in decimal). That number can be changed, of course, to the maximum integer, but this runs pretty quickly as is.

Example call: `echo '3 2' | ruby golfscript.rb h.gs`

Output:

```
[[1 0 0 0 0 0 0 0 0 1] [1 0 0 1] [5 1 3] [2 0 1] [8 1]]
[[1 0 0 1 0 0 1 0 0 1] [1 1 1 1] [5 8 5] [2 4 9] [9 9]]
[[1 1 0 0 0 0 0 0 0 1 1] [3 0 0 3] [1 5 3 9] [6 0 3] [24 3]]
[[1 1 0 1 1 0 1 1 0 1 1] [3 3 3 3] [1 7 5 5] [6 13 11] [27 27]]
[[1 0 1 0 0 0 0 0 0 1 0 1] [5 0 0 5] [2 5 6 5] [10 0 5] [40 5]]
[[1 0 1 0 1 0 0 1 0 1 0 1] [5 2 2 5] [2 7 0 9] [10 9 5] [42 21]]
...

```

---
Tags: code-challenge, number, fastest-code, palindrome
---