@@ -51,34 +51,30 @@ func ExampleInt_Scan() {
51
51
// Output: 18446744073709551617
52
52
}
53
53
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.
56
56
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 )
60
60
61
- // initialize limit as 10^99 ( the smallest integer with 100 digits)
61
+ // Initialize limit as 10^99, the smallest integer with 100 digits.
62
62
var limit big.Int
63
63
limit .Exp (big .NewInt (10 ), big .NewInt (99 ), nil )
64
64
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
74
71
}
72
+ fmt .Println (a ) // 100-digit Fibonacci number
75
73
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 ))
82
78
83
79
// Output:
84
80
// 1344719667586153181419716641724567886890850696275767987106294472017884974410332069524504824747437757
0 commit comments