Table of contents  
Introduction  
Understanding Prime Numbers  
Checking Prime Numbers in Python  
Sample Problems 
Prime numbers are an essential concept in mathematics and computer science. They play a significant role in various algorithms and are widely used in programming. In this article, we will explore how to check if a number is prime using Python. We will provide simple code examples and explanations to help beginners grasp the concept easily.
A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself. In other words, it cannot be divided evenly by any other number except 1 and itself.
Let's dive into some code examples that demonstrate different approaches to check whether a given number is prime or not.
One of the simplest ways to check if a number is prime is to iterate from 2 to the square root of the number and check if it has any divisors within that range.
import math
def is_prime_basic(num):
if num < 2:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
# Testing the function
print(is_prime_basic(17)) # Output: True
print(is_prime_basic(25)) # Output: False
Explanation:
We can optimize the above approach further by considering some mathematical properties of prime numbers. We only need to iterate up to the square root of the number, and we can skip even numbers greater than 2 since they are not prime.
import math
def is_prime_optimized(num):
if num < 2:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3, int(math.sqrt(num)) + 1, 2):
if num % i == 0:
return False
return True
# Testing the function
print(is_prime_optimized(17)) # Output: True
print(is_prime_optimized(25)) # Output: False
Explanation:
Problems 1: Check if the number 29 is prime.
print(is_prime_optimized(29)) # Output: True
Problems 2: Check if the number 100 is prime.
print(is_prime_optimized(100)) # Output: False
Problems 3: Find the sum of all prime numbers between 1 and 50.
primes_sum = sum(num for num in range(1, 51) if is_prime_optimized(num))
print(primes_sum) # Output: 328
In this article, we explored how to check for prime numbers in Python using two different methods. We learned that prime numbers are integers greater than 1 with no divisors other than 1 and itself. The basic and optimized iteration methods provided simple and efficient ways to determine if a number is prime. By understanding these concepts and applying the code examples, you can solve problems involving prime numbers and build more complex algorithms in your Python programs.
49 videos38 docs18 tests

49 videos38 docs18 tests


Explore Courses for Software Development exam
