publicclassSimpleSieve { publicstaticint[] sieve(int n){ int[] mark = newint[n+1]; //元素值为0代表是素数 intcounter=0; for (inti=2; i <= n; i++){ if (mark[i] == 0){ counter++; for (intj=2 * i; j <= n; j += i){ mark[j] = 1; } } } int[] primes = newint[counter]; counter = 0; for (inti=2; i <= n; i++){ if (mark[i] == 0) primes[counter++] = i; } return primes; }
publicstaticvoidmain(String[] args){ int[] ans = SimpleSieve.sieve(100); for (int e: ans) { System.out.println(e + " "); } } }
python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
from typing importList
deferatosthenes_sieve(n: int) -> List[int]: ans = [] marks = [True] * n for i inrange(2, n): if marks[i]: ans.append(i) for j inrange(i + i, n, i): marks[j] = False return ans
if __name__ == "__main__": print(eratosthenes_sieve(100))