0

I would like to take a number like 96, call squareRoot(96), and get a return of "4√6".

I have tried many different versions of

  • generating a list of the prime factors
  • finding the perfect divisors
  • using recursive implementations
  • iterative implementations
  • HashMaps
  • lists

but nothing seems to work. It is driving me crazy! I can provide the functions I wrote to find the factors, but I don't think they are particularly complicated.

Sam
  • 261
  • 2
  • 11

1 Answers1

0

I found an answer in python here (python, square root simplification function) and translated it into Kotlin:

fun squareRoot(n: Int): Pair<Int, Int> {
    var radical = n
    var coefficient = 1
    for (i in 2..radical) {
        if (radical % (i * i) == 0) {
            coefficient *= i
            radical /= i * i
            for (j in 2..radical) {
                if (radical % (j * j) == 0) {
                    coefficient *= j
                    radical /= j * j
                }
            }
        }
    }
    return Pair(coefficient, radical)
}
Sam
  • 261
  • 2
  • 11
  • Do you need to keep a list of `roots`? If I'm reading it correctly, you could just update `coefficient` as you go along, and avoid the overhead of the list and its traversal. (And wouldn't a name such as `radicle` be more meaningful than `number1`?) – gidds Aug 13 '20 at 20:25
  • (Might be interesting to extend this to cube &c roots, by providing the power as another parameter?) – gidds Aug 13 '20 at 20:27
  • True about the list. Edited. – Sam Aug 13 '20 at 20:48
  • You should accept your own answer - [nothing wrong with that](https://stackoverflow.com/help/self-answer). – desertnaut Aug 17 '20 at 22:59