Computer Hardware Club

1-Second Prime Showdown

Write a Python algorithm that finds the highest number of primes in exactly 1.0 second. Don't be lame, don't cheat.

Finding prime numbers is a foundational concept in computer science, deeply tied to cryptography and hardware benchmarking. Today, we're testing not just your math skills, but how well you can optimize code to utilize CPU cycles and memory most efficiently.

  1. A Closed Book: No Google, StackOverflow, ChatGPT, Claude, etc. If it feels like cheating, it probably is. The only reference you can use is the offline documentation search at the bottom of this page.
  2. B The Defense: To claim the winning title, you must explain exactly how and why your optimization works (similar to the Troubleshooting Workshop). If you can't explain your code, you will be banned from the club forever and expelled from OSU. No pressure though.
  3. C Time Limit: Your code must stop executing exactly 1 second after the calculation loop begins (handled by the starter code).
  4. D Output: Your script must print the total count of primes found. No hardcoded arrays.
  5. E Language: Python 3. Yes, Python is slow. Shut up CS nerd.
  6. F Sequentiality: Primes must be computed sequentially. This means you can just jump to 1 billion and start there. First prime computed must be 2.
  7. G Final Test: All submissions will be tested on the host's laptop for fairness. The highest valid count wins.

This baseline works, but it's incredibly slow. Copy it into a file named prime.py and run it to see your starting score.

prime.py
import time

def is_prime(n):
    """A very naive and slow way to check for a prime number."""
    if n <= 1:
        return False
    # Checks every single number up to n
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

def main():
    print("Starting Prime Hunt for exactly 1.0 second...")
    start_time = time.time()
    duration = 1.0

    prime_count = 0
    current_number = 2

    # Run the loop until 1 second has passed
    while (time.time() - start_time) < duration:
        if is_prime(current_number):
            prime_count += 1
        current_number += 1

    print("\n--- TIME'S UP! ---")
    print(f"Total primes found: {prime_count}")
    print(f"Highest number checked: {current_number - 1}")

if __name__ == "__main__":
    main()

The starter code won't win. It relies on brute force. To reach the millions, you need to fundamentally change the way you think about prime numbers. Discuss these concepts with your team, and use them as a springboard to get your development started:

Phase 1

Stop Doing Expensive Math

  • The starter code uses the modulo operator (%) inside a nested loop. Division and modulo are computationally expensive for a CPU.
  • Addition (+) is incredibly fast. Is there a way to find prime numbers using only addition? Think about how multiples work.
Phase 2

Invert the Problem

  • Right now, the code takes a number (like 97) and looks backwards to see if it has any divisors. This is wasted effort.
  • What if you start at the bottom with known primes (2, 3, 5) and look forwards? If you know 2 is prime, you immediately know that 4, 6, 8, and 10 are not.
  • How can you "cross out" multiples as you go, rather than checking individual numbers?

Phase 3

The Memory Bottleneck

  • If you use the Phase 2 method, you will need to keep a massive "ledger" to track which numbers are crossed out and which are still prime.
  • If you build a list of millions of standard Python booleans, the memory footprint will exceed your CPU's L1/L2 cache. The CPU will waste precious milliseconds waiting for data to fetch from main RAM.
  • Search your Offline Documentation below for ways to store a massive array of true/false values using the smallest amount of memory possible.

Open your terminal, navigate to your folder, and run:

$ python3 prime.py

What number did it return? Great, make it go higher.

Search this local Python reference by concept, syntax, or optimization keyword. No internet needed.

Keyboard: / focus, ↑/↓ move, Enter expand, Esc clear.