3

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.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
user10634
  • 31
  • 1

4 Answers4

1

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

enter image description here

bill s
  • 68,936
  • 4
  • 101
  • 191
  • 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
1

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
wxffles
  • 14,246
  • 1
  • 43
  • 75
1

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:

  • Because of the use of Defer this output can also be used as input without any additional steps.

  • By limiting FactorInteger to only two factors (using the second parameter) and specifying a maximum IntegerLength we limit the overhead of this processing.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
0

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}

*)
ciao
  • 25,774
  • 2
  • 58
  • 139