# How do I prevent exponents from being expanded when displaying text

I have a power of 2 in a list, and I want it to show as $2^{31}$ (2 with exponent 31), not 2147483648.

I've tried this:

aa={2^31,1103515245,12345,12345}
Text[Style[aa[[1]]]]
Text[Style[HoldForm[2^31]]]


The first form shows 2147483648. The second form shows correctly, but not when it is in a list.

-
Somewhat related: (7741), (7799) – Mr.Wizard Feb 11 '14 at 16:06

It's a little bit roundabout, but this may work:

aa = {2^31, 1103515245, 12345, 12345};
If[IntegerQ[Log[2, #]], 2^ToString[Log[2, #]], #] & /@ aa


-
This is more or less exactly what I need -- I also have other powers like 5^^15 and 13^^13 in aa, but it gets me the output I wanted. Thanks! – user10634 Feb 10 '14 at 19:43

You could factor any integers and pick out the ones that are a power of a prime:

ClearAll@powerForm
powerForm[n_Integer /; With[{factors = FactorInteger@n},
Length@factors == 1 && Last@Last@factors != 1]] :=
powerForm[Sequence @@ First@FactorInteger[n]];
Format[powerForm[b_, e_]] ^:= HoldForm[b^e];
powerForm[n_] := n;


To use:

powerForm /@ aa

-
Yes, this is exactly what I was looking for. It is a lot more meaningful to see 5^^13 than 1220703125. – user10634 Feb 10 '14 at 22:05

Since you apparently only want to effect the output I recommend using $PrePrint as follows: $PrePrint =
# /. n_Integer /; IntegerLength[n] < 100 :>
With[{fi = FactorInteger[n, 2] /. {{b_, x_ /; x > 1}} :> Defer[b^x]},
fi /; ! ListQ[fi]
] &;


After evaluating this every integer in the output that factors to a single prime power will be replaced with that form. (You can place it in the Kernel/init.m file to load it at start-up.)

1220703125 + 343 a

5^13 + a 7^3


Details:

-

This will do it for any numbers that can be represented as some power of a distinct integer, and the list is still usable for calculation by releasing the hold, unlike converting to string, etc.

keepPowers[lst_] := Module[{powers, reps},
powers = HoldForm[#1^#2] & @@@ # & /@ FactorInteger[lst];
reps = lst[[#]] -> powers[[#]][[1]] & /@
Pick[Range@Length@lst, powers, _?(Length[#] == 1 &)];
Replace[lst, reps, 1]];

lst = {2^31, 1103515245, 12345, 12345, 3^30, 2^20*3^10, 5^5}

keepPowers[lst]

ReleaseHold[%]

(*

{2147483648, 1103515245, 12345, 12345, 205891132094649, 61917364224, 3125}

{2^31, 1103515245, 12345, 12345, 3^30, 61917364224, 5^5}

{2147483648, 1103515245, 12345, 12345, 205891132094649, 61917364224, 3125}

*)

-