mirror of
https://github.com/golang/go
synced 2024-11-23 16:40:03 -07:00
math/big: Added small complete example of big.Int usage
Updates #11241 Change-Id: I9639c4f66cf805a57b087c9f648d3918df105d86 Reviewed-on: https://go-review.googlesource.com/11034 Reviewed-by: Robert Griesemer <gri@golang.org>
This commit is contained in:
parent
e38bcb58d7
commit
f0fee976aa
@ -49,3 +49,31 @@ func ExampleInt_Scan() {
|
|||||||
}
|
}
|
||||||
// Output: 18446744073709551617
|
// Output: 18446744073709551617
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Example_fibonacci demonstrates how to use big.Int to compute the smallest
|
||||||
|
// Fibonacci number with 100 decimal digits, and find out whether it is prime.
|
||||||
|
func Example_fibonacci() {
|
||||||
|
// create and initialize big.Ints from int64s
|
||||||
|
fib1 := big.NewInt(0)
|
||||||
|
fib2 := big.NewInt(1)
|
||||||
|
|
||||||
|
// initialize limit as 10^99 (the smallest integer with 100 digits)
|
||||||
|
var limit big.Int
|
||||||
|
limit.Exp(big.NewInt(10), big.NewInt(99), nil)
|
||||||
|
|
||||||
|
// loop while fib1 is smaller than 1e100
|
||||||
|
for fib1.Cmp(&limit) < 0 {
|
||||||
|
fib1, fib2 = fib2, fib1.Add(fib1, fib2)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(fib1) // 100-digits fibonacci number
|
||||||
|
|
||||||
|
// Test fib1 for primality. The ProbablyPrimes parameter sets the number
|
||||||
|
// of Miller-Rabin rounds to be performed. 20 is a good value.
|
||||||
|
isPrime := fib1.ProbablyPrime(20)
|
||||||
|
fmt.Println(isPrime) // false
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// 1344719667586153181419716641724567886890850696275767987106294472017884974410332069524504824747437757
|
||||||
|
// false
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user