Certainly! Below is the rewritten algorithm using the Sieve of Euler approach, optimized with Numba's just-in-time compilation and utilizing bit-packed arrays to efficiently represent prime flags. This implementation leverages bit manipulation to minimize memory usage and enhance cache performance.
Key Enhancements:
-
Sieve of Euler: Unlike the traditional Sieve of Eratosthenes, the Sieve of Euler ensures that each composite number is marked exactly once with its smallest prime factor. This reduces redundant operations.
-
Bit-Packed Flags: Instead of using one byte (uint8) per number to represent primality, this implementation uses bits within an array of uint64 integers. Each bit represents the primality of an odd number, significantly reducing memory usage.
-
Optimized Prime Storage: Primes are stored in a Numba typed list, allowing efficient iteration and manipulation within the Numba-compiled function.
Implementation Details:
-
Odd Number Representation: Since even numbers greater than 2 are not prime, the algorithm only considers odd numbers starting from 3. Each bit in the is_prime array represents an odd number: bit 0 corresponds to 3, bit 1 to 5, and so on.
-
Bit Manipulation:
- To check if a number is prime: Determine its corresponding bit and check if it's set.
- To mark a multiple as composite: Clear the corresponding bit.
-
Sieve of Euler Logic: For each prime found, multiply it by existing primes to mark composites. This ensures each composite is marked only once by its smallest prime factor.
Complete Rewritten Code:
import numpy as np
import time
from numba import njit
from numba.typed import List
@njit
def sieve_euler_bitpacked(limit):
if limit < 2:
return 0
# Calculate the number of odd numbers >=3 up to the limit
num_bits = (limit - 1) // 2
# Each uint64 can hold 64 bits
num_words = (num_bits + 63) // 64
# Initialize all bits to 1 (assuming all are prime initially)
is_prime = np.full(num_words, 0xFFFFFFFFFFFFFFFF, dtype=np.uint64)
# Initialize a typed list for storing primes and add 2 manually
primes = List()
primes.append(2)
for number in range(3, limit + 1, 2):
# Calculate the bit index for the current number
k = (number - 3) // 2
word = k // 64
bit = k % 64
# Check if the current number is marked as prime
if (is_prime[word] & (1 << bit)) != 0:
primes.append(number)
# Iterate through the primes list to mark multiples
for p in primes:
if p > number:
break
multiple = p * number
if multiple > limit:
break
if multiple % 2 == 0:
continue # Skip even multiples
# Calculate the bit index for the multiple
mk = (multiple - 3) // 2
m_word = mk // 64
m_bit = mk % 64
# Mark the multiple as composite by clearing its bit
is_prime[m_word] &= ~(1 << m_bit)
# If p is the current number, no need to check further
if p == number:
break
return len(primes)
# Measure the execution time
if __name__ == "__main__":
n = 100_000_000 # Example limit
start_time = time.time()
prime_count_euler = sieve_euler_bitpacked(n)
end_time = time.time()
print(f"Number of primes up to {n}: {prime_count_euler}")
print(f"Time taken: {end_time - start_time:.2f} seconds")
Explanation of the Code:
-
Initialization:
- Bit-Packed Array (
is_prime): Represents the primality of odd numbers starting from 3. Each bit corresponds to an odd number (3, 5, 7, ...). All bits are initially set to 1 (prime).
- Primes List (
primes): A Numba typed list that starts with 2, the only even prime.
-
Main Loop (for number in range(3, limit + 1, 2)):
- Check Primality: For each odd number, determine its corresponding bit in
is_prime. If the bit is set, the number is prime.
- Add to Primes: If the number is prime, append it to the
primes list.
- Mark Multiples:
- Iterate through existing primes up to the current prime.
- Calculate the multiple (
p * number).
- If the multiple is within the limit and odd, calculate its bit position and clear the corresponding bit in
is_prime to mark it as composite.
- If the prime
p is equal to the current number, break to ensure each composite is marked only once.
-
Counting Primes: After completing the sieve, the length of the primes list gives the total number of primes up to the specified limit.
-
Performance Measurement: The script measures and prints the execution time for counting primes up to 100,000,000.
Performance Considerations:
-
Memory Efficiency: By using bit-packed arrays, the memory footprint is significantly reduced compared to using one byte per number.
-
Cache Performance: Accessing bits packed within uint64 words can lead to better cache utilization, enhancing performance.
-
Sieve of Euler Benefits: Ensures that each composite is marked only once, reducing redundant operations inherent in the traditional Sieve of Eratosthenes.
Sample Output:
Number of primes up to 100000000: 5761455
Time taken: XX.XX seconds
Note: The actual execution time (XX.XX seconds) will depend on your hardware specifications.
Final Remarks:
This implementation effectively combines the Sieve of Euler's efficiency with bit-packed representations to optimize both memory usage and computation speed. Utilizing Numba's JIT compilation further accelerates the sieve, making it suitable for large-scale prime counting tasks.