GCD Calculation in C

Level 389 keystrokes

Calculates the greatest common divisor using the Euclidean algorithm.

C code

// Find the GCD of 48 and 18
1int a = 48, b = 18;
// Euclid: GCD(a, b) = GCD(b, a % b), repeated until b is 0
2while (b != 0) {
// Save b before it is overwritten
3 int t = b;
// The new b is the remainder: (48, 18) → (18, 12) → (12, 6) → (6, 0)
4 b = a % b;
// The new a is the old b
5 a = t;
6}
// When b reaches 0, a is the GCD: 6
7printf("GCD: %d", a);

Output

GCD: 6
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • =× 6
  • ;× 5
  • ,× 2
  • "× 2
  • (× 2
  • )× 2
  • %× 2
  • :× 1
  • !× 1
  • {× 1

More C examples at level 3

← C typing practice