Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big int ranges in Go

Tags:

go

bigint

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
}
like image 978
Benjamin Rowell Avatar asked Nov 30 '25 12:11

Benjamin Rowell


1 Answers

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)
    }
}
like image 50
Stephen Weinberg Avatar answered Dec 02 '25 03:12

Stephen Weinberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!