generatePrimes static method
Generates a list of prime numbers up to a specified limit using the Sieve of Eratosthenes algorithm.
The SSieve of Eratosthenes is an efficient algorithm for finding all prime numbers up to any given limit. It works by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime number, 2.
Parameters:
limit: The upper bound (inclusive) up to which prime numbers should be generated. Must be an integer.
Returns:
A List<int> containing all prime numbers from 2 up to limit.
Returns an empty list if limit is less than 2.
Implementation
static List<int> generatePrimes(int limit) {
if (limit < 2) return [];
final isPrime = List.filled(limit + 1, true);
isPrime[0] = false;
isPrime[1] = false;
for (int i = 2; i * i <= limit; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= limit; j += i) {
isPrime[j] = false;
}
}
}
final primes = <int>[];
for (int i = 2; i <= limit; i++) {
if (isPrime[i]) {
primes.add(i);
}
}
return primes;
}