2

Is there a way to loop over intervals between two big int values, x and y, in Go?

for i: = x; i < y; i++ {
    // do something
}

1 Answer 1

9

Working with big numbers can be kind of clunky because you need to create a big.Int for constants. Other than that, it is a straight forward replacement of each segment of the for statement to one made to deal with big ints.

http://play.golang.org/p/pLSd8yf9Lz

package main

import (
    "fmt"
    "math/big"
)

var one = big.NewInt(1)

func main() {
    start := big.NewInt(1)
    end := big.NewInt(5)
    // i must be a new int so that it does not overwrite start
    for i := new(big.Int).Set(start); i.Cmp(end) < 0; i.Add(i, one) {
        fmt.Println(i)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.