4

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?

creidhne
  • 5,055
  • 4
  • 20
  • 28
Arji
  • 1,134
  • 7
  • 10

2 Answers2

8

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].

7

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

xx + yy*y

Carl Woll
  • 130,679
  • 6
  • 243
  • 355