The
Euclidean algorithm
, orEuclid's algorithm
, is an efficient method forcomputing the greatest common divisor (GCD) of two integers (numbers)
, the largest number that divides them both without a remainder
Usage:
- reducing
fractions
to theirsimplest form
- performing
division
inmodular arithmetic
- Computations using this algorithm form part of the
cryptographic
protocols that are used to secure internet communications, and in methods for breaking these cryptosystems byfactoring large composite numbers
- solve
Diophantine
equations, such as finding numbers that satisfy multiple congruences according to theChinese remainder theorem
, to constructcontinued fractions
, and to find accuraterational approximations
to real numbers. - a basic tool for proving theorems in
number theory
such as Lagrange’s four-square theorem - the
uniqueness of prime factorizations
Pseudocode
function gcd(a, b)
while b ≠ 0
t := b
b := a mod b
a := t
return a
Swift Implementation
func gcd(_ a: Int, _ b: Int) -> Int {
var t = 0
var a = a
var b = b
while b != 0 {
t = a
a = b
b = t%b
}
return a
}
Comments
Join the discussion for this article at here . Our comments is using Github Issues. All of posted comments will display at this page instantly.