Powers and roots of large numbers in Go?

Viewed 97

I am trying to port (for learning) my Python code below to Go -- the Python works fine.

for n in range (81522017,81522025):
     b = int(str(n) + str(n+1)+str(n+2))
     if b**(1/3) % 1 == 0:
         print(n,b)
         break

//solution 81522019   and  815220198152202081522021

So in Go, I end up with:

package main

import (
    "fmt"
    "strconv"
    "math"
)

func main() {
  
    for n:=81522017; n<81522025;n++{
      b:=(strconv.Itoa(n)+strconv.Itoa(n+1)+strconv.Itoa(n+2))
      bFloat, _ := (strconv.ParseFloat(b,64))
    
      if math.Mod((math.Pow((bFloat),(1.0/3.0))),1.0)   == 0 {
          fmt.Println(n,bFloat)  
      }    
    }
}

The condition in the if statement is never met and therefore the solution is not displayed. I think this has something to do with precision of handling floats.

Ultimately, I am looking at taking the cube root of a large integer (815220198152202081522021 in this case) and checking to see if it is a pure integer -- hence the %1 in the Python code.

What am I missing -- there must be an easier way to do this....

Any help / pointers greatly received.

1 Answers

I think it's because you use Float % integers, let's say 69.777 % 1.0, it has to be 0.777, not 0, so it doesn't in if condition. You try this solution.This is add int() haha.

if int(math.Mod((math.Pow((bFloat),(1.0/3.0))),1.0)) == 0 {
    fmt.Println(n,bFloat)  
}

Related