1

I'm trying to build a program that let's you multiply two square roots and display the answer in surd form if the answer isn't an integer.

I've seen answers here and here, although I don't understand C++ and C#, so I don't have a clue on what to do. The first thing I've done is multiply the two numbers inside the square roots together, then I can display the answer if it is an integer, but if it isn't it completely messes up.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

2 Answers2

2

Try using SymPy:

>>>import sympy
>>>sympy.sqrt(8)
2*sqrt(2)
isaa_ctaylor
  • 311
  • 1
  • 7
2

I don't see a better way than by factoring the given numbers, summing the multiplicities of the prime factors, extracting the even parts of the multiplicities and forming the square root of the products.

E.g.

√(84.375)=√(2²3.7.3.5³)=√(2²3²5³7)=2.3.5√(5.7)=30√35
  • 2
    There is a better way. If you're multiplying two square-free surds, the GCD is going to be the integer. That can be calculated by the Euclidean algorithm without any factoring required. – btilly Jun 23 '22 at 01:08
  • 1
    @btilly: can you explain how you exploit that to solve the given problem ? –  Jun 23 '22 at 06:44
  • 1
    If the numbers are pairs `[a, b]` representing `a sqrt(b)` then `[a, b]` times `[c, d`] is `[ac + gcd(b, d), bd / gcd(bd)^2]`. It doesn't help if you start with them not in that form though. – btilly Jun 23 '22 at 14:16
  • 1
    @btilly: ok, I missed that the numbers could be given in surd form. (Then every factor of the root part has exactly multiplicity one, and common factors get multiplicity two.) Would you like to enter an answer, or shall I update mine ? –  Jun 23 '22 at 15:02
  • 1
    I'm not, rereading the question, positive that they could be given in surd form. – btilly Jun 23 '22 at 15:29
  • If the result is not an integer, then I would want it to be in surd form. – Praseodymium-141 Jun 25 '22 at 08:35
  • @Bli231957: I am afraid that yo missed the discussion. –  Jun 25 '22 at 09:46