How would you calculate the sum of prime numbers up to N?

DSA
Medium
Infosys
104.1K views

Candidates need to generate prime numbers up to a limit N and sum them. This tests knowledge of number theory and sieve algorithms.

Why Interviewers Ask This

This question evaluates a candidate's familiarity with mathematical algorithms and optimization techniques. It distinguishes between brute-force primality testing and more efficient methods like the Sieve of Eratosthenes. Interviewers assess the ability to balance code simplicity with performance requirements for larger inputs.

How to Answer This Question

Start by defining what a prime number is. Discuss the naive approach of checking divisibility for each number up to N, noting its O(N*sqrt(N)) complexity. Then introduce the Sieve of Eratosthenes as a superior alternative with O(N log log N) complexity. Explain how the sieve marks non-prime multiples efficiently. Conclude with how to accumulate the sum while iterating through the marked primes.

Key Points to Cover

  • Sieve of Eratosthenes
  • Time complexity reduction
  • Boolean array usage
  • Summation logic

Sample Answer

The most efficient way is to use the Sieve of Eratosthenes. I create a boolean array of size N+1, initially marking all entries as true. Starting from 2, I mark all multiples of each prime as false. After processing up to sqrt(N), the remaining true values represent prime numbers. I then iterate through the array, summing the indices that remain true. This approach reduces the time complexity significantly compared to checking each number individually, making it suitable for large values of N.

Common Mistakes to Avoid

  • Using trial division for every number
  • Incorrect boundary conditions in the sieve loop
  • Forgetting to exclude 0 and 1

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 35 DSA questionsBrowse all 65 Infosys questions