-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgcd3.cpp
More file actions
38 lines (33 loc) · 782 Bytes
/
gcd3.cpp
File metadata and controls
38 lines (33 loc) · 782 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//===========================================================
//gcd3.cpp
//Computes the greatest common divisor of two non-negative
//integers a and b without dividing numbers
//===========================================================
#include <cassert>
using namespace std;
int gcd(int a, int b)
{
assert(not(a==0 and b==0));//they can't both be zero
assert(a>=0);
assert(b>=0);
int i=a;//make local copies
int j=b;
while((i!=j) and (j!=0) and (i!=0))
{
//loop invariant gcd(i,j)=gcd(a,b)
if(i>j)
{
i=i-j;//reduce i but leave GCD unchanged
}
else
{
j=j-i;//reduce j but leave GCD unchanged
}
}
//Now only special cases are possible
if(i==0) //GCD(0,j)=j
{
return j;
}
return i; //GCD(i,i)=i or GCD(i,0)=i
}