#!/usr/bin/env python3 """ Scenario 1: The Obvious CPU Hog =============================== This program counts prime numbers using trial division. It's intentionally slow to demonstrate profiling. EXERCISES: 1. Run with: time python3 prime_slow.py 2. Profile with: python3 -m cProfile -s cumtime prime_slow.py 3. Generate flamegraph: py-spy record -o prime_slow.svg -- python3 prime_slow.py 4. Identify the hot function, then see prime_fast.py for the optimized version """ import sys def is_prime(n): """Check if n is prime using trial division.""" if n < 2: return False if n == 2: return True if n % 2 == 0: return False # Check odd divisors up to sqrt(n) i = 3 while i * i <= n: if n % i == 0: return False i += 2 return True def count_primes(limit): """Count all primes up to limit.""" count = 0 for n in range(2, limit + 1): if is_prime(n): count += 1 return count def main(): limit = 1_000_000 # Adjust this to change runtime if len(sys.argv) > 1: limit = int(sys.argv[1]) print(f"Counting primes up to {limit}...") result = count_primes(limit) print(f"Found {result} primes") if __name__ == "__main__": main()