Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a | 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. | 3 // BSD-style license that can be found in the LICENSE file. |
| 4 | 4 |
| 5 library dart.pkg.math; | 5 library dart.pkg.math; |
| 6 | 6 |
| 7 // Placeholder library, reserved for future extension. | 7 /** |
| 8 * Computes the greatest common divisor between [a] and [b]. | |
| 9 * | |
| 10 * [a] and [b] must be non-negative integers. | |
|
Lasse Reichstein Nielsen
2014/08/20 12:17:02
-> Both `a` and `b` must be non-negative integers.
srawlins
2014/08/25 05:43:54
Done.
| |
| 11 */ | |
| 12 int gcd(int a, int b) { | |
| 13 if (a is! int) throw new ArgumentError(a); | |
| 14 if (b is! int) throw new ArgumentError(b); | |
| 15 if (a.isNegative || b.isNegative) { | |
| 16 throw new RangeError("a and b must not be negative; received $a and $b."); | |
|
Lasse Reichstein Nielsen
2014/08/20 12:17:02
"Both a and b ...
srawlins
2014/08/25 05:43:53
Done.
| |
| 17 } | |
| 18 | |
| 19 // Iterative Binary GCD algorithm. | |
| 20 if (a == 0) return b; | |
| 21 if (b == 0) return a; | |
| 22 int powerOfTwo = 1; | |
| 23 int temp; | |
| 24 while (((a | b) & 1) == 0) { | |
| 25 powerOfTwo *= 2; | |
| 26 a ~/= 2; | |
| 27 b ~/= 2; | |
| 28 } | |
| 29 | |
| 30 while (a.isEven) a ~/= 2; | |
| 31 | |
| 32 do { | |
| 33 while (b.isEven) b ~/= 2; | |
| 34 if (a > b) { | |
| 35 temp = b; | |
| 36 b = a; | |
| 37 a = temp; | |
| 38 } | |
| 39 b -= a; | |
| 40 } while (b != 0); | |
| 41 | |
| 42 return a * powerOfTwo; | |
| 43 } | |
| OLD | NEW |