Prime Check in C

Level 3157 keystrokes

Checks if a number is prime by testing divisibility up to its square root.

C code

// Assume prime (1 = true) until a divisor is found
1int n = 17, isPrime = 1;
// i * i <= n means i <= √n: a larger divisor would pair with a smaller one already tested
2for (int i = 2; i * i <= n; i++) {
// A divisor proves n is not prime; break stops further checks. For 17, i = 2, 3, 4 all fail
3 if (n % i == 0) { isPrime = 0; break; }
4}
// isPrime is still 1, so the ternary picks "prime": 17 is prime
5printf("%d is %s", n, isPrime ? "prime" : "not prime");

Output

17 is prime
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.

  • =× 7
  • ;× 6
  • "× 6
  • ,× 3
  • (× 3
  • )× 3
  • %× 3
  • {× 2
  • }× 2
  • +× 2

More C examples at level 3

← C typing practice