g | x | w | all
Bytes Lang Time Link
109Maple251015T202748Zdharr

Maple, 109 bytes

s->map(z->`if`(z::`*`,[op(1,z),op(2,z)^2],`if`(z::`^`,[1,z^2],[z,1])),[op(..-2,combine(evala(1/s)+x,sqrt))]);

Input is sqrt(2)+sqrt(3)+sqrt(5), Output is [[-1/12, 30], [1/4, 2], [1/6, 3]] meaning -1/12*sqrt(30)+1/4*sqrt(2)+1/6*sqrt(3). The output sqrts are always of positive integers.

I thought this would be my shortest code ever, since s->evala(1/s) does all the math giving a sum of terms. However, Maple's automatic simplification gets in the way:

  1. sqrt(6) gets simplified to sqrt(2)*sqrt(3), requiring the combine(..,sqrt) code.
  2. The output can look like sqrt(3)/2 not (1/2)*sqrt(3), but internally is (1/2)*3^(1/2)
  3. A term can have no sqrt in it, e.g., the first example just gives 1, so needs to have a sqrt(1) affixed to it.

All these mean that the parts need to be dissected and several special cases taken care of:

  1. If there is only 1 term (as in the first example), then add +x as a second term so it is a sum, then later use op(..2,..) to remove that term.
  2. For (3) above, the term is not a product so we want [term,1].
  3. If the coefficient is 1, the term is also not a product but is a power (type ^), so we want [1,term^2] Otherwise we want [op(1,z),op(2,z)^2] meaning [coefficient,square of sqrt(..)].