Created
October 31, 2023 17:25
-
-
Save gigamonkey/d15693b561a3a8de98eb5c6d9dcac058 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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