Find n-th root of a big number

321 views
Skip to first unread message

Hau Phan

unread,
Sep 21, 2020, 1:11:44 PM9/21/20
to golang-nuts
i can't find get n-th root in document of go big package so i decided to do it myself using newton's method. i found a solution at https://www.geeksforgeeks.org/n-th-root-number/ and start to implement in go. but my code only work fine for base 2. other base result gone too far from correct.

Anyone could show me where am i wrong.

Here's my code

```go
package main

import (
"fmt"
"math/big"
"math/rand"
)

// PowFloat return x^n
func PowFloat(x *big.Float, n int64) *big.Float {
result := new(big.Float).SetInt64(1)
for i := 0; i < int(n); i++ {
result.Mul(result, x)
}
return result
}

// GetNthRoothFloat get nth root of a using newton's method
func GetNthRoothFloat(a *big.Float, n int64) *big.Float {
N := new(big.Float).SetInt64(n)
xPre := new(big.Float).SetInt64(int64(rand.Intn(10) + 1))
eps := new(big.Float).SetFloat64(0.00000000001)
delX := new(big.Float).SetInt64(2147483647)
xK := new(big.Float).SetInt64(0)

for delX.Cmp(eps) > 0 {
t1 := new(big.Float).Sub(N, new(big.Float).SetFloat64(1.0)) // t1 = n-1
t1 = t1.Mul(t1, xPre)                                       // t1 = (N-1) * xPre
t2 := new(big.Float).Quo(a, PowFloat(xPre, n-1))            // t2 = a/( xPre^(n-1) )
t3 := new(big.Float).Add(t1, t2)                            // t3 = t1 + t2
xK.Quo(t3, N)
delX = new(big.Float).Sub(xK, xPre)
delX.Abs(delX)
xPre = xK.Copy(xK)
}
return xK
}

func main() {
t := new(big.Float).SetInt64(64)
fmt.Println(GetNthRoothFloat(t, 3))
}
```

Rob Pike

unread,
Sep 22, 2020, 3:13:38 AM9/22/20
to Hau Phan, golang-nuts
I'm not going to debug you program for you - you'll learn more doing it yourself, but I glanced at it and saw immediately that you're missing an easy optimization. Raising a number to an integer power can be done much faster by repeated squaring according to the bit pattern of the exponent. I'll leave that cryptic comment alone to let you puzzle it out yourself. (Don't look it up; it's much more fun to figure out.)

-rob


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/5a38a7fe-426b-4f94-905e-79b42dcaa611n%40googlegroups.com.

Nasir Hussain

unread,
Sep 22, 2020, 3:55:04 AM9/22/20
to Rob Pike, Hau Phan, golang-nuts

roger peppe

unread,
Sep 22, 2020, 10:55:18 AM9/22/20
to Nasir Hussain, Rob Pike, Hau Phan, golang-nuts
Reply all
Reply to author
Forward
0 new messages