# Write x^3 as x*x*x

I use mathematica compute functions I need for some external coding. However I can't use terms like x^2+y^3 since my programming language needs this term written as x*x+y*y*y. I would love to copy and paste the results from mathematica so how do I convert these terms?

• Something like StringReplace["x^2+y^3", a : LetterCharacter ~~ "^" ~~ n : DigitCharacter :> StringRiffle[ConstantArray[a, FromDigits[n]], "*"]]? – J. M.'s torpor Jan 14 at 11:28
• Kinda works but kinda not since mathematica dont uses ^ to write a power. – Arjihad Jan 14 at 11:29
• You can first use ToString@InputForm[expr] to get a string with powers written in ^ notation – Hausdorff Jan 14 at 11:40
• Or you can look at this previous post: Post – Pino Savana Jan 14 at 11:42
• I asked a similar question ten years ago (!!!) about tweaking the output of "CForm" (to change Power to repeated multiplication); Leonid Schifrin wrote a great reply that solved my problem. So it is really quite interesting to me to see the approaches mentioned to this question. – Daniel Chisholm Jan 14 at 17:37

If you want it in string form you can do it like this

x^3 /. Power -> (StringRiffle[#, "*"] &@ConstantArray[#1, #2] &)


"x * x * x"

This makes use of the fact that x^3 is internally written as Power[x,3].

• Works. Thank you! – Arjihad Jan 14 at 12:00
• x^3 /. Power[a_, n_] :> Inactive[Times] @@ ConstantArray[a, n] is another way to do it. This makes it easy to convert back as well with Activate. – Sjoerd Smit Jan 14 at 14:41
• also x^2 + y^3 /. Power -> Apply[Inactive @ Times] @* ConstantArray – kglr Jan 14 at 19:55

Since you mention another language, here's a method using CForm:

Unprotect[Power];

Power /: Format[x_Symbol^n_Integer?Positive, CForm] := SequenceForm @@ Riffle[
ConstantArray[x, n],
Format["*", OutputForm]
]

Protect[Power];


Example:

x^2+y^3 //CForm

x*x + y*y*y