Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Binary GCD algorithm

From Wikipedia, the free encyclopedia
Algorithm for computing the greatest common divisor

Visualisation of using the binary GCD algorithm to find the greatest common divisor (GCD) of 36 and 24. Thus, the GCD is 22 × 3 = 12.

Thebinary GCD algorithm, also known asStein's algorithm or thebinary Euclidean algorithm,[1][2] is an algorithm that computes thegreatest common divisor (GCD) of two nonnegative integers. Stein's algorithm uses simpler arithmetic operations than the conventionalEuclidean algorithm; it replaces division witharithmetic shifts, comparisons, and subtraction.

Although the algorithm in its contemporary form was first published by the physicist and programmer Josef Stein in 1967,[3] it was known by the 2nd century BCE, in ancient China.[4]

Algorithm

[edit]

The algorithm finds the GCD of two nonnegative numbersu{\displaystyle u} andv{\displaystyle v} by repeatedly applying these identities:

  1. gcd(u,0)=u{\displaystyle \gcd(u,0)=u}: everything divides zero, andu{\displaystyle u} is the largest number that dividesu{\displaystyle u}.
  2. gcd(2u,2v)=2gcd(u,v){\displaystyle \gcd(2u,2v)=2\cdot \gcd(u,v)}:2{\displaystyle 2} is a common divisor.
  3. gcd(u,2v)=gcd(u,v){\displaystyle \gcd(u,2v)=\gcd(u,v)} ifu{\displaystyle u} is odd:2{\displaystyle 2} is then not a common divisor.
  4. gcd(u,v)=gcd(u,vu){\displaystyle \gcd(u,v)=\gcd(u,v-u)} ifu,v{\displaystyle u,v} odd anduv{\displaystyle u\leq v}.

As GCD is commutative (gcd(u,v)=gcd(v,u){\displaystyle \gcd(u,v)=\gcd(v,u)}), those identities still apply if the operands are swapped:gcd(0,v)=v{\displaystyle \gcd(0,v)=v},gcd(2u,v)=gcd(u,v){\displaystyle \gcd(2u,v)=\gcd(u,v)} ifv{\displaystyle v} is odd, etc.

Implementation

[edit]

While the above description of the algorithm is mathematically correct, the binary GCD algorithm performs more loop iterations that the Euclidean one, so it only offers a performance advantage if those iterations are substantially faster. Performant software implementations typically differ from it in a few notable ways:

  • eschewing repeatedtrial division by2{\displaystyle 2} in favour of thecount trailing zeros primitive and a singlebit shift, which is functionally equivalent to repeatedly applying identity 3, but much faster;
  • expressing the algorithmiteratively rather thanrecursively: the resulting implementation can be laid out to avoid repeated work, invoking identity 2 at the start and maintaining as invariant that both numbers are odd upon entering the loop, which only needs to implement identities 3 and 4; and
  • making the loop's bodybranch-free except for its exit conditionv==0:unpredictable branches can have a large, negative impact on performance.[5][6]

The following is an implementation of the algorithm inC. After the shift at the top of the main loop, the variablesu andv hold the values(u-1)/2 and(v-1)/2. This elimination of the least-significant bit leaves room for the signed differenceu-v to be computed on the next line without overflow.

// Count trailing zeros.  This is a pedagogical example only;// for efficiency use __builtin_ctzll() or similar.staticintctz(uint64_tn){ints=0,t;while((t=n&15)==0){n>>=4;s+=4;}returns+((0x12131210>>2*t)&3);}uint64_tgcd(uint64_tu,uint64_tv){uint64_tuv=u|v;if(!u||!v)returnuv;// Identity #1u>>=ctz(u)+1;inttz=ctz(v);for(;;){v>>=tz+1;// Identity #3v-=u;// Identity #4if(v==0)break;tz=ctz(v);// ctz(v) == ctz(-v), so do this early// if ((int64_t)v < 0) { u += v; v = -v; }uint64_tmask=(int64_t)v>>63;u+=v&mask;// Branch-free conditional addv^=mask;// Branch-free conditional negate}return(2*u+1)<<ctz(uv);// Identity #2}


The following is an implementation of the algorithm inRust exemplifying those differences, adapted fromuutils. The conditional exchange ofu{\displaystyle u} andv{\displaystyle v} (ensuringuv{\displaystyle u\leq v}) compiles down toconditional moves;[7]:

usestd::cmp::min;usestd::mem::swap;pubfngcd(mutu:u64,mutv:u64)->u64{// Base cases: gcd(n, 0) = gcd(0, n) = nifu==0{returnv;}elseifv==0{returnu;}// Using identities 2 and 3:// gcd(2ⁱ u, 2ʲ v) = 2ᵏ gcd(u, v) with u, v odd and k = min(i, j)// 2ᵏ is the greatest power of two that divides both 2ⁱ u and 2ʲ vleti=u.trailing_zeros();u>>=i;letj=v.trailing_zeros();v>>=j;letk=min(i,j);loop{// u and v are odd at the start of the loopdebug_assert!(u%2==1,"u = {} should be odd",u);debug_assert!(v%2==1,"v = {} should be odd",v);// Swap if necessary so u ≤ vifu>v{(u,v)=(v,u);}// Identity 4: gcd(u, v) = gcd(u, v-u) as u ≤ v and u, v are both oddv-=u;// v is now evenifv==0{// Identity 1: gcd(u, 0) = u// The shift by k is necessary to add back the 2ᵏ factor that was removed before the loopreturnu<<k;}// Identity 3: gcd(u, 2ʲ v) = gcd(u, v) as u is oddv>>=v.trailing_zeros();}}

Note: The implementation above acceptsunsigned (non-negative) integers; given thatgcd(u,v)=gcd(±u,±v){\displaystyle \gcd(u,v)=\gcd(\pm {}u,\pm {}v)}, the signed case can be handled as follows:

/// Computes the GCD of two signed 64-bit integers/// The result is unsigned and not always representable as i64: gcd(i64::MIN, i64::MIN) == 1 << 63pubfnsigned_gcd(u:i64,v:i64)->u64{gcd(u.unsigned_abs(),v.unsigned_abs())}

Complexity

[edit]

Asymptotically, the algorithm requiresO(n){\displaystyle O(n)} steps, wheren{\displaystyle n} is the number of bits in the larger of the two numbers, as every two steps reduce at least one of the operands by at least a factor of2{\displaystyle 2}. Each step involves only a few arithmetic operations (O(1){\displaystyle O(1)} with a small constant); when working withword-sized numbers, each arithmetic operation translates to a single machine operation, so the number of machine operations is on the order ofn{\displaystyle n}, i.e.log2(max(u,v)){\displaystyle \log _{2}(\max(u,v))}.

For arbitrarily large numbers, theasymptotic complexity of this algorithm isO(n2){\displaystyle O(n^{2})},[8] as each arithmetic operation (subtract and shift) involves a linear number of machine operations (one per word in the numbers' binary representation).If the numbers can be represented in the machine's memory,i.e. each number'ssize can be represented by a single machine word, this bound is reduced to:O(n2log2n){\displaystyle O\left({\frac {n^{2}}{\log _{2}n}}\right)}

This is the same as for the Euclidean algorithm, though a more precise analysis by Akhavi and Vallée proved that binary GCD uses about 60% fewer bit operations.[9]

Extensions

[edit]

The binary GCD algorithm can be extended in several ways, either to output additional information, deal witharbitrarily large integers more efficiently, or to compute GCDs in domains other than the integers.

Theextended binary GCD algorithm, analogous to theextended Euclidean algorithm, fits in the first kind of extension, as it provides theBézout coefficients in addition to the GCD: integersa{\displaystyle a} andb{\displaystyle b} such thatau+bv=gcd(u,v){\displaystyle a\cdot {}u+b\cdot {}v=\gcd(u,v)}.[10][11][12]

In the case of large integers, the best asymptotic complexity isO(M(n)logn){\displaystyle O(M(n)\log n)}, withM(n){\displaystyle M(n)} the cost ofn{\displaystyle n}-bit multiplication; this is near-linear and vastly smaller than the binary GCD algorithm'sO(n2){\displaystyle O(n^{2})}, though concrete implementations only outperform older algorithms for numbers larger than about 64 kilobits (i.e. greater than 8×1019265). This is achieved by extending the binary GCD algorithm using ideas from theSchönhage–Strassen algorithm for fast integer multiplication.[13]

The binary GCD algorithm has also been extended to domains other than natural numbers, such asGaussian integers,[14]Eisenstein integers,[15] quadratic rings,[16][17] andinteger rings ofnumber fields.[18]

Historical description

[edit]

An algorithm for computing the GCD of two numbers was known in ancient China, under theHan dynasty, as a method to reduce fractions:

If possible halve it; otherwise, take the denominator and the numerator, subtract the lesser from the greater, and do that alternately to make them the same. Reduce by the same number.

— Fangtian – Land surveying,The Nine Chapters on the Mathematical Art

The phrase "if possible halve it" is ambiguous,[4]

  • if this applies wheneither of the numbers become even, the algorithm is the binary GCD algorithm;
  • if this only applies whenboth numbers are even, the algorithm is similar to theEuclidean algorithm.

See also

[edit]

References

[edit]
  1. ^Brent, Richard P. (13–15 September 1999).Twenty years' analysis of the Binary Euclidean Algorithm. 1999 Oxford-Microsoft Symposium in honour of Professor Sir Antony Hoare. Oxford.
  2. ^Brent, Richard P. (November 1999).Further analysis of the Binary Euclidean algorithm (Technical report). Oxford University Computing Laboratory.arXiv:1303.2772. PRG TR-7-99.
  3. ^Stein, J. (February 1967), "Computational problems associated with Racah algebra",Journal of Computational Physics,1 (3):397–405,Bibcode:1967JCoPh...1..397S,doi:10.1016/0021-9991(67)90047-2,ISSN 0021-9991
  4. ^abKnuth, Donald (1998),Seminumerical Algorithms,The Art of Computer Programming, vol. 2 (3rd ed.), Addison-Wesley,ISBN 978-0-201-89684-8
  5. ^Kapoor, Rajiv (21 February 2009)."Avoiding the Cost of Branch Misprediction".Intel Developer Zone.
  6. ^Lemire, Daniel (15 October 2019)."Mispredicted branches can multiply your running times".
  7. ^Godbolt, Matt."Compiler Explorer". Retrieved4 February 2024.
  8. ^"GNU MP 6.1.2: Binary GCD".
  9. ^Akhavi, Ali; Vallée, Brigitte (2000),"Average Bit-Complexity of Euclidean Algorithms",Proceedings ICALP'00, Lecture Notes Computer Science 1853:373–387,CiteSeerX 10.1.1.42.7616
  10. ^Knuth 1998, p. 646, answer to exercise 39 of section 4.5.2
  11. ^Menezes, Alfred J.; van Oorschot, Paul C.; Vanstone, Scott A. (October 1996)."§14.4 Greatest Common Divisor Algorithms"(PDF).Handbook of Applied Cryptography. CRC Press. pp. 606–610.ISBN 0-8493-8523-7. Retrieved9 September 2017.
  12. ^Cohen, Henri (1993). "Chapter 1 : Fundamental Number-Theoretic Algorithms".A Course In Computational Algebraic Number Theory.Graduate Texts in Mathematics. Vol. 138.Springer-Verlag. pp. 17–18.ISBN 0-387-55640-0.
  13. ^Stehlé, Damien;Zimmermann, Paul (2004),"A binary recursive gcd algorithm"(PDF),Algorithmic number theory, Lecture Notes in Comput. Sci., vol. 3076, Springer, Berlin, pp. 411–425,CiteSeerX 10.1.1.107.8612,doi:10.1007/978-3-540-24847-7_31,ISBN 978-3-540-22156-2,MR 2138011,S2CID 3119374, INRIA Research Report RR-5050.
  14. ^Weilert, André (July 2000)."(1+i)-ary GCD Computation in Z[i] as an Analogue to the Binary GCD Algorithm".Journal of Symbolic Computation.30 (5):605–617.doi:10.1006/jsco.2000.0422.
  15. ^Damgård, Ivan Bjerre; Frandsen, Gudmund Skovbjerg (12–15 August 2003).Efficient Algorithms for GCD and Cubic Residuosity in the Ring of Eisenstein Integers. 14th International Symposium on the Fundamentals of Computation Theory.Malmö, Sweden. pp. 109–117.doi:10.1007/978-3-540-45077-1_11.
  16. ^Agarwal, Saurabh; Frandsen, Gudmund Skovbjerg (13–18 June 2004).Binary GCD Like Algorithms for Some Complex Quadratic Rings. Algorithmic Number Theory Symposium.Burlington, VT, USA. pp. 57–71.doi:10.1007/978-3-540-24847-7_4.
  17. ^Agarwal, Saurabh; Frandsen, Gudmund Skovbjerg (20–24 March 2006).A New GCD Algorithm for Quadratic Number Rings with Unique Factorization. 7th Latin American Symposium on Theoretical Informatics. Valdivia, Chile. pp. 30–42.doi:10.1007/11682462_8.
  18. ^Wikström, Douglas (11–15 July 2005).On the l-Ary GCD-Algorithm in Rings of Integers. Automata, Languages and Programming, 32nd International Colloquium. Lisbon, Portugal. pp. 1189–1201.doi:10.1007/11523468_96.

Further reading

[edit]

Covers the extended binary GCD, and a probabilistic analysis of the algorithm.

Covers a variety of topics, including the extended binary GCD algorithm which outputsBézout coefficients, efficient handling of multi-precision integers using a variant ofLehmer's GCD algorithm, and the relationship between GCD andcontinued fraction expansions of real numbers.

An analysis of the algorithm in the average case, through the lens offunctional analysis: the algorithms' main parameters are cast as adynamical system, and their average value is related to theinvariant measure of the system'stransfer operator.

External links

[edit]


Primality tests
Prime-generating
Integer factorization
Multiplication
Euclideandivision
Discrete logarithm
Greatest common divisor
Modular square root
Other algorithms
  • Italics indicate that algorithm is for numbers of special forms
Retrieved from "https://en.wikipedia.org/w/index.php?title=Binary_GCD_algorithm&oldid=1338408796"
Category:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp