Skip to content

Instantly share code, notes, and snippets.

@gigamonkey
Created October 31, 2023 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gigamonkey/d15693b561a3a8de98eb5c6d9dcac058 to your computer and use it in GitHub Desktop.
Save gigamonkey/d15693b561a3a8de98eb5c6d9dcac058 to your computer and use it in GitHub Desktop.
/*
* A number is prime if it is not divisible by any number other than 1 and
* itself. 1 is not prime. Thus you can test whether a number greater than 1 is
* prime by checking whether it is divisible by any smaller number greater than
* one.
*/
public class Primes {
public boolean isPrime(int n) {
for (int f = 2; f <= Math.sqrt(n); f++) {
if (n % f == 0) return false;
}
return n != 1;
}
public int numberOfPrimesBelow(int bound) {
int count = 0;
for (int n = 2; n < bound; n++) {
if (isPrime(n)) {
count++;
}
}
return count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment