Skip to content
Justice Tech School

Example: Primes and GCD

Combine loops and functions to solve small problems.

Example
#include <stdio.h>

int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
int main(void) {
  for (int n = 2; n <= 20; n++) {
    int p = 1;
    for (int d = 2; d * d <= n; d++) if (n % d == 0) { p = 0; break; }
    if (p) printf("%d ", n);
  }
  printf("\n%d\n", gcd(48, 18));
  return 0;
}

Result

2 3 5 7 11 13 17 19 
6

Exercise

Greatest common divisor.

gcd(a, b) uses 

Quiz Test

What is gcd(48, 18)?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.