mirror of https://github.com/golang/go.git
math/big: refine Fibonacci example
Change-Id: Id9e8c3f89e021b9f389ab3c8403e6a8450fa9f5f Reviewed-on: https://go-review.googlesource.com/11231 Reviewed-by: Robert Griesemer <gri@golang.org> Reviewed-by: Josh Bleecher Snyder <josharian@gmail.com>
This commit is contained in:
parent
2a5745d81e
commit
0c247bf41b
|
|
@ -51,34 +51,30 @@ func ExampleInt_Scan() {
|
||||||
// Output: 18446744073709551617
|
// Output: 18446744073709551617
|
||||||
}
|
}
|
||||||
|
|
||||||
// Example_fibonacci demonstrates how to use big.Int to compute the smallest
|
// This example demonstrates how to use big.Int to compute the smallest
|
||||||
// Fibonacci number with 100 decimal digits, and find out whether it is prime.
|
// Fibonacci number with 100 decimal digits and to test whether it is prime.
|
||||||
func Example_fibonacci() {
|
func Example_fibonacci() {
|
||||||
// create and initialize big.Ints from int64s
|
// Initialize two big ints with the first two numbers in the sequence.
|
||||||
fib1 := big.NewInt(0)
|
a := big.NewInt(0)
|
||||||
fib2 := big.NewInt(1)
|
b := big.NewInt(1)
|
||||||
|
|
||||||
// initialize limit as 10^99 (the smallest integer with 100 digits)
|
// Initialize limit as 10^99, the smallest integer with 100 digits.
|
||||||
var limit big.Int
|
var limit big.Int
|
||||||
limit.Exp(big.NewInt(10), big.NewInt(99), nil)
|
limit.Exp(big.NewInt(10), big.NewInt(99), nil)
|
||||||
|
|
||||||
// loop while fib1 is smaller than 1e100
|
// Loop while a is smaller than 1e100.
|
||||||
for fib1.Cmp(&limit) < 0 {
|
for a.Cmp(&limit) < 0 {
|
||||||
// Compute the next Fibonacci number:
|
// Compute the next Fibonacci number, storing it in a.
|
||||||
// t1 := fib2
|
a.Add(a, b)
|
||||||
// t2 := fib1.Add(fib1, fib2) // Note that Add "assigns" to fib1!
|
// Swap a and b so that b is the next number in the sequence.
|
||||||
// fib1 = t1
|
a, b = b, a
|
||||||
// fib2 = t2
|
|
||||||
// Using Go's multi-value ("parallel") assignment, we can simply write:
|
|
||||||
fib1, fib2 = fib2, fib1.Add(fib1, fib2)
|
|
||||||
}
|
}
|
||||||
|
fmt.Println(a) // 100-digit Fibonacci number
|
||||||
|
|
||||||
fmt.Println(fib1) // 100-digit Fibonacci number
|
// Test a for primality.
|
||||||
|
// (ProbablyPrimes' argument sets the number of Miller-Rabin
|
||||||
// Test fib1 for primality. The ProbablyPrimes parameter sets the number
|
// rounds to be performed. 20 is a good value.)
|
||||||
// of Miller-Rabin rounds to be performed. 20 is a good value.
|
fmt.Println(a.ProbablyPrime(20))
|
||||||
isPrime := fib1.ProbablyPrime(20)
|
|
||||||
fmt.Println(isPrime)
|
|
||||||
|
|
||||||
// Output:
|
// Output:
|
||||||
// 1344719667586153181419716641724567886890850696275767987106294472017884974410332069524504824747437757
|
// 1344719667586153181419716641724567886890850696275767987106294472017884974410332069524504824747437757
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue