Tutorialspoint
Problem
Solution
Submissions

Count the Number of Prime Numbers in a Given Range

Certification: Basic Level Accuracy: 64.1% Submissions: 39 Points: 15

Write a Python program that counts the number of prime numbers within a given range.

Example 1
  • Input: start = 10, end = 20
  • Output: 4
  • Explanation:
    • Step 1: Check each number from 10 to 20 to determine if it's prime.
    • Step 2: A number is prime if it's greater than 1 and has no divisors other than 1 and itself.
    • Step 3: Prime numbers in the range [10, 20] are: 11, 13, 17, 19.
    • Step 4: There are 4 prime numbers in this range.
    • Step 5: Return 4.
Example 2
  • Input: start = 1, end = 10
  • Output: 4
  • Explanation:
    • Step 1: Check each number from 1 to 10 to determine if it's prime.
    • Step 2: A number is prime if it's greater than 1 and has no divisors other than 1 and itself.
    • Step 3: Prime numbers in the range [1, 10] are: 2, 3, 5, 7.
    • Step 4: There are 4 prime numbers in this range.
    • Step 5: Return 4.
Constraints
  • 1 ≤ startend ≤ 10^6
  • Time Complexity: O((end-start) * sqrt(end)) where end-start is the size of the range
  • Space Complexity: O(1)
NumberControl StructuresGoogleWalmart
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Implement a function to check if a number is prime
  • For prime checking, only check divisibility up to the square root of the number

Steps to solve by this approach:

 Step 1: Create a helper function to determine if a number is prime.

 Step 2: In the helper function, handle special cases (numbers <= 1 are not prime, 2 and 3 are prime).
 Step 3: Optimize primality testing using divisibility by 2, 3, and numbers of form 6k+=1.
 Step 4: Initialize a counter for prime numbers found in the range.
 Step 5: Iterate through each number in the specified range (inclusive).
 Step 6: For each number, check if it's prime using the helper function and increment the counter if true.
 Step 7: Return the final count of prime numbers in the range.

Submitted Code :