## Base-26 Arithmetic

### March 23, 2012

A reader named Prashant recently wrote to suggest an exercise in base-26 arithmetic:

Write a function that takes two base-26 numbers in which digits are represented by letters with A=0, B=1, … Z=25 and returns their product using the same notation. As an example, CSGHJ × CBA = FNEUZJA.

Prashant was worried that the problem was specific to C/C++, but that’s not an issue.

Your task is to write the base-26 multiplication function. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2

PHP CLI:

Maybe it’s too early for me and I made a mistake, but I think that “CSGHJ” x “CBA” = “FOFVAJA”; here’s my Python:

Changing bases seems to work fine, i.e.

`int_to_b26(b26_to_int(s)) == s`

as far as I can tell.Woops, never mind. I tested against 25, instead of 26; let me work on this (make sure I don’t have any more embarassing mistakes) and get back to you later.

Yup. Changing all 25s to 26s does the trick. I won’t repost, since I’ve already filled this page with my comments.

Here is a Perl solution

Ok, I should stop, but this is good J practice for me.

Typically, I wouldn’t then bother with defining the multiply function and instead just use:

Of course, I could always define it if I wanted to:

The trick here, besides having base-conversion built-in (“#.”), is the “under” adverb, “&.”. “f &. g” translates to

J is pretty clever about deducing the inverses of functions, and you can always explicitly set the inverse to a function, if it can’t figure it out.

Hey! Here’s the C code :

Hey! there’s a flaw :P replace the last 3 lines with:

an erlang example.

“FNEUZJA” = base26:mult(“CSGHJ”, “CBA”).

In Haskell, but written for conciseness at the expense of speed and safety. :-)

Looks long now that I’ve seen the other comments, but here’s one in Common Lisp:

Another CL version, in a slightly different style from that of Jonathan.

>>> WholeSym(WholeSym(‘CSGHJ’) * WholeSym(‘CBA’))

WholeSym(‘FNEUZJA’)

>>> W = WholeSym

>>> W( W(‘C’) * W(‘BL’) * W(‘CJ’) * W(‘FV’) * W(‘VHJ’) * W(‘MVUTMJAWRZ’) )

WholeSym(‘PROGRAMMINGPRAXIS’)

Also python version

My solution written in Go lang: https://gist.github.com/2944246

@Siyuan The python one is a bit weird … int_to_b26(25) == ‘z’ int_to_b26(26) == ‘ba’ < should be 'aa'