
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Number of Prime Numbers Within a Given Range in Python
When it is required to find the prime numbers within a given range of numbers, the range is entered and it is iterated over. The ‘%’ modulus operator is used to find the prime numbers.
Example
Below is a demonstration of the same
lower_range = 670 upper_range = 699 print("The lower and upper range are :") print(lower_range, upper_range) print("The prime numbers between", lower_range, "and", upper_range, "are:") for num in range(lower_range, upper_range + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num)
Output
The lower and upper range are : 670 699 The prime numbers between 670 and 699 are: 673 677 683 691
Explanation
The upper range and lower range values are entered and displayed on the console.
The numbers are iterated over.
It is checked to see if they are greater than 1 since 1 is neither a prime number nor a composite number.
The numbers are iterated, and ‘%’ with 2.
This way the prime number is found, and displayed on console.
Else it breaks out of the loop.
Advertisements