Simplify Radicals: Python code

I’m exploring if it’s possible to create a function in GeoGebra that would take an integer as input and create a simplified radical as output. For instance, it would take \(20\) as input and return \(2\sqrt{5}\) as output. I don’t know a way, so if someone does, please tell me. (Edit: There is the SurdText command, which does exactly what I want. I still wish there was a way to create one’s own commands for use in GeoGebra textboxes… I’ll explore the CAS.)

In the meantime, I wrote the function for formatting the output in Python:

from math import floor
def simpleradical(n):
  nabs = abs(n)
  trial = floor(nabs**0.5)
  coeff = 1
  while trial > 1:
    if n % (trial**2) == 0:
      coeff = trial
      trial = 0
    trial -= 1
  remainder = nabs // coeff**2
  return coeff, remainder

def simpleradicalformat(n):
  if not(isinstance(n, int)):
    return "Input must be an integer"
  elif n == 0 or n == 1:
    return str(n)
  else:
    coeff, remainder = simpleradical(n)
    returnstring = ''
    if coeff > 1:
      returnstring = str(coeff)
    if n < 0:
      returnstring += "i"     
    if remainder > 1:
      returnstring += '√' + str(remainder)
  return returnstring

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.