Tutorialspoint
Problem
Solution
Submissions

Print Prime Numbers in a Given Range

Certification: Basic Level Accuracy: 55.36% Submissions: 56 Points: 10

Write a Python program that prints all prime numbers within a given range from start to end (inclusive).

Example 1
  • Input: start = 10, end = 20
  • Output: [11, 13, 17, 19]
  • Explanation:
    • Step 1: For each number from 10 to 20, check 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: 11, 13, 17, and 19 are prime because they have no divisors other than 1 and themselves.
    • Step 4: Return the list of prime numbers found in the range.
Example 2
  • Input: start = 30, end = 40
  • Output: [31, 37]
  • Explanation:
    • Step 1: For each number from 30 to 40, check 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: 31 and 37 are prime because they have no divisors other than 1 and themselves.
    • Step 4: Return the list of prime numbers found in the range.
Constraints
  • 1 ≤ startend ≤ 10^5
  • Time Complexity: O(n * sqrt(n)) where n is the size of the range
  • Space Complexity: O(k) where k is the number of prime numbers in the range
NumberControl StructuresFacebookDropbox
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

  • Use a helper function to check if a number is prime
  • A number is prime if it is not divisible by any integer from 2 to sqrt(n)
  • Optimize by checking only odd numbers after 2

Steps to solve by this approach:

 Step 1: Define a nested helper function to check if a number is prime.

 Step 2: In the helper function, handle edge cases and use optimized primality testing.
 Step 3: Initialize an empty list to store prime numbers found.
 Step 4: Iterate through each number in the specified range (inclusive).
 Step 5: Use list comprehension to filter numbers that are prime according to the helper function.
 Step 6: Return the list of prime numbers found in the range.

Submitted Code :