What is the best way to find the sum of all prime numbers up to N?

Technical
Medium
Infosys
129K views

This question challenges candidates to implement a prime number sieve or efficient checking method. It tests mathematical optimization skills.

Why Interviewers Ask This

This problem is designed to evaluate a candidate's ability to apply mathematical optimizations in coding. A naive approach checks every number individually, which is inefficient for large N. Interviewers look for knowledge of algorithms like the Sieve of Eratosthenes to reduce time complexity significantly.

How to Answer This Question

Begin by explaining the brute-force method and its limitations regarding time complexity. Introduce the Sieve of Eratosthenes as a more efficient alternative. Walk through the steps of marking non-prime numbers in a boolean array. Discuss the final step of summing the remaining primes and analyze the overall time and space trade-offs.

Key Points to Cover

  • Use Sieve of Eratosthenes
  • Mark multiples of primes
  • Sum remaining true indices
  • Optimize over brute force

Sample Answer

For small values of N, checking each number individually might suffice, but for larger inputs, I would use the Sieve of Eratosthenes. This algorithm marks multiples of each prime starting from 2, effectively filtering out non-primes. After sieving, I iterate through the boolean array to sum the indices marked as prime. This reduces the time complexity from O(N*sqrt(N)) to O(N log log N), making it highly scalable for large ranges.

Common Mistakes to Avoid

  • Checking primality for every number individually
  • Incorrectly initializing the sieve array
  • Including 1 as a prime number

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 78 Technical questionsBrowse all 65 Infosys questions