gcd: Finds the greatest common divider of two integers

Description Usage Arguments Value Author(s) References Examples

View source: R/gcd.R

Description

Finds the greatest common divider (gcd) of two integers using Euclid's algorithm.

Usage

1
gcd(a, b)

Arguments

a

First value.

b

Second value.

Note: a can be larger than b or vice versa.

Value

Returns a positive integer greater or equal to one that is the greatest common divider between the two given values.

Author(s)

Henrik Bengtsson

References

[1] Alexander Bogomolny, Euclid's Algorithm, Feb 2003, http://www.cut-the-knot.com/blue/Euclid.shtml

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Example of Euclide's algorithm:
#
# Let a = 2322 and b = 654. Calculate gcd(a,b)!
#
# 2322 = 654*3 + 360   gcd(2322, 654) = gcd(654, 360)
# 654  = 360*1 + 294   gcd(654, 360)  = gcd(360, 294)
# 360  = 294*1 + 66    gcd(360, 294)  = gcd(294, 66)
# 294  = 66*4 + 30     gcd(294, 66)   = gcd(66, 30)
# 66   = 30*2 + 6      gcd(66, 30)    = gcd(30, 6)
# 30   = 6*5           gcd(30, 6)     = 6
#
# In other words, gcd(2322,654) = 6.

print( gcd(2322, 654) )     # 6

HenrikBengtsson/R.basic documentation built on May 6, 2019, 11:51 p.m.