35 lines
496 B
Plaintext
35 lines
496 B
Plaintext
|
|
boolean isPrime(int n) {
|
||
|
|
if (n < 2) return false;
|
||
|
|
if (n == 2) return true;
|
||
|
|
if (n % 2 == 0) return false;
|
||
|
|
for (int i = 3; i * i <= n; i = i + 2) {
|
||
|
|
if (n % i == 0) return false;
|
||
|
|
}
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
isPrime(2)
|
||
|
|
isPrime(17)
|
||
|
|
isPrime(100)
|
||
|
|
isPrime(997)
|
||
|
|
|
||
|
|
for (int i = 2; i <= 50; i++) {
|
||
|
|
if (isPrime(i)) {
|
||
|
|
System.out.println(i);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
int countPrimes(int limit) {
|
||
|
|
int count = 0;
|
||
|
|
for (int i = 2; i <= limit; i++) {
|
||
|
|
if (isPrime(i)) count++;
|
||
|
|
}
|
||
|
|
return count;
|
||
|
|
}
|
||
|
|
|
||
|
|
countPrimes(100)
|
||
|
|
countPrimes(1000)
|
||
|
|
|
||
|
|
%methods
|
||
|
|
%quit
|