Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(404)

Side by Side Diff: pkg/math/lib/math.dart

Issue 475463005: Implement math.gcd in dart. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Move gcd to pkg/math; move tests; fix implementation; split bigint tests Created 6 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « no previous file | tests/lib/lib.status » ('j') | tests/lib/math/math_package_bigint_test.dart » ('J')
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
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 }
OLDNEW
« no previous file with comments | « no previous file | tests/lib/lib.status » ('j') | tests/lib/math/math_package_bigint_test.dart » ('J')

Powered by Google App Engine
This is Rietveld 408576698