Skip to content

Commit 0c247bf

Browse files
committed
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>
1 parent 2a5745d commit 0c247bf

File tree

1 file changed

+17
-21
lines changed

1 file changed

+17
-21
lines changed

src/math/big/example_test.go

+17-21
Original file line numberDiff line numberDiff line change
@@ -51,34 +51,30 @@ func ExampleInt_Scan() {
5151
// Output: 18446744073709551617
5252
}
5353

54-
// Example_fibonacci demonstrates how to use big.Int to compute the smallest
55-
// Fibonacci number with 100 decimal digits, and find out whether it is prime.
54+
// This example demonstrates how to use big.Int to compute the smallest
55+
// Fibonacci number with 100 decimal digits and to test whether it is prime.
5656
func Example_fibonacci() {
57-
// create and initialize big.Ints from int64s
58-
fib1 := big.NewInt(0)
59-
fib2 := big.NewInt(1)
57+
// Initialize two big ints with the first two numbers in the sequence.
58+
a := big.NewInt(0)
59+
b := big.NewInt(1)
6060

61-
// initialize limit as 10^99 (the smallest integer with 100 digits)
61+
// Initialize limit as 10^99, the smallest integer with 100 digits.
6262
var limit big.Int
6363
limit.Exp(big.NewInt(10), big.NewInt(99), nil)
6464

65-
// loop while fib1 is smaller than 1e100
66-
for fib1.Cmp(&limit) < 0 {
67-
// Compute the next Fibonacci number:
68-
// t1 := fib2
69-
// t2 := fib1.Add(fib1, fib2) // Note that Add "assigns" to fib1!
70-
// fib1 = t1
71-
// fib2 = t2
72-
// Using Go's multi-value ("parallel") assignment, we can simply write:
73-
fib1, fib2 = fib2, fib1.Add(fib1, fib2)
65+
// Loop while a is smaller than 1e100.
66+
for a.Cmp(&limit) < 0 {
67+
// Compute the next Fibonacci number, storing it in a.
68+
a.Add(a, b)
69+
// Swap a and b so that b is the next number in the sequence.
70+
a, b = b, a
7471
}
72+
fmt.Println(a) // 100-digit Fibonacci number
7573

76-
fmt.Println(fib1) // 100-digit Fibonacci number
77-
78-
// Test fib1 for primality. The ProbablyPrimes parameter sets the number
79-
// of Miller-Rabin rounds to be performed. 20 is a good value.
80-
isPrime := fib1.ProbablyPrime(20)
81-
fmt.Println(isPrime)
74+
// Test a for primality.
75+
// (ProbablyPrimes' argument sets the number of Miller-Rabin
76+
// rounds to be performed. 20 is a good value.)
77+
fmt.Println(a.ProbablyPrime(20))
8278

8379
// Output:
8480
// 1344719667586153181419716641724567886890850696275767987106294472017884974410332069524504824747437757

0 commit comments

Comments
 (0)