sieve.ts 685 B

12345678910111213141516171819202122232425262728
  1. enum State {
  2. Maybe = 0,
  3. Prime,
  4. NotPrime,
  5. }
  6. export function primes(limit: number): number[] {
  7. const all: number[] = Array(limit + 1).fill(State.Maybe);
  8. all[0] = State.NotPrime;
  9. all[1] = State.NotPrime;
  10. for (let i = 2; i <= limit; i++) {
  11. if (all[i] === State.NotPrime) {
  12. continue;
  13. }
  14. all[i] = State.Prime;
  15. for (let j = 2; j <= limit / i; j++) {
  16. all[i * j] = State.NotPrime;
  17. }
  18. }
  19. const res: number[] = [];
  20. let property: keyof typeof all;
  21. for (property in all) {
  22. if (all[property] === State.Prime) {
  23. res.push(Number(property));
  24. }
  25. }
  26. return res;
  27. }