Big Int Arithmetic Beyond Int64 Range
math/big computes factorials and powers that overflow int64, with Exp for exponents and IsInt64 to detect values that no longer fit in machine words.
Code
package main
import (
"fmt"
"math"
"math/big"
)
func main() {
// 上限参照:int64 最大值约 9.22e18,而 25! 约 1.55e25,早已装不下
fmt.Println("int64 max:", int64(math.MaxInt64))
// big.Int 连乘求 25!:Mul 支持接收者与操作数别名,累乘惯用写法
fact := new(big.Int).SetInt64(1)
for i := int64(2); i <= 25; i++ {
fact.Mul(fact, big.NewInt(i))
}
fmt.Println("25! =", fact.String())
// Exp 求 2^100:第三个参数为 nil 表示不做模运算
pow2 := new(big.Int).Exp(big.NewInt(2), big.NewInt(100), nil)
fmt.Println("2^100 =", pow2.String())
// IsInt64 判断结果是否仍能装回机器字长,避免塞回 int64 时静默溢出
fmt.Println("25! fits int64:", fact.IsInt64())
}The mechanics
Big Int Arithmetic Beyond Int64 Range reduces to the function main.
The file repeats itself only inside for i := int64(2); i <= 25; i++.
Caveats
- It is dependency-free in the strict sense — the import list, if any, is empty of packages.
Using it
Running the file prints labeled results such as int64 max:, 25! =, 2^100 = — each operation’s effect is visible in the output.
Key statements
pow2 := new(big.Int).Exp(big.NewInt(2), big.NewInt(100), nil)
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.
FAQ
- What does Big Int Arithmetic Beyond Int64 Range print when run?
- No setup needed: run the file and look for labeled lines like `int64 max:`, `25! =`, `2^100 =` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.