Did you know that your bank passwords, WhatsApp messages, and credit card transactions are protected because of prime numbers?
Yes, those same numbers you studied in school, like 2, 3, 5, 7, and 11, quietly keep the digital world safe.
So when you write a simple Python program to check if a number is prime, you’re actually stepping into the same world that powers cybersecurity and encryption algorithms.
Think about it:
- That random code your OTP uses? Possibly derived from a prime-based generator.
- That secure website you log into? Protected by large prime pairs in RSA encryption.
Primes aren’t just math; they’re digital superheroes hiding in plain sight.
Now let’s explore how to find them using Python.
What You’ll Learn in This Blog
In this guide, you’ll learn:
- What prime numbers are (with examples)
- How to check prime numbers in Python — step by step
- Optimized and advanced methods (for efficiency and large numbers)
- Applications of primes in programming, cryptography, and beyond
What are Prime Numbers?
A prime number is a number greater than 1 that cannot be expressed as the product of two A prime number is a number greater than 1 that cannot be expressed as the product of two smaller positive integers.
In simple terms, prime numbers are divisible only by 1 and themselves.
The sequence of prime numbers begins with:
2, 3, 5, 7, 11, 13, 17, 19, and so on.
Definition of Prime Numbers
Formally, a prime number is defined as a natural number greater than one that possesses no factors except for one and itself.
Here are the first few prime numbers:
- 2 → (the only even prime number)
- 3
- 5
- 7
- 11
- 13
- 17
Examples of Prime Numbers
- 2 is prime as its only divisors are 1 and 2.
- 3 is prime because it can only be divided by 1 and 3.
- 5 is prime because it is divisible only by 1 and 5.
- 11 is prime because it is divisible by 1 and 11.
Importance of Prime Numbers in Programming
Prime numbers are more than just a concept in math; they are the backbone of modern computer security and efficient algorithms.
In programming, prime numbers are used in:
Cryptography (Data Security):
Prime numbers greatly facilitate encryption algorithms (such as RSA) by generating digital keys with extremely large prime powers to help keep your sensitive information safe, from online purchases to WhatsApp messages.
Hashing & Data Storage:
Prime numbers are used in constructing efficient hash functions to reduce the collisions in databases, caching, memory allocation, etc.
Optimized Algorithms:
The majority of other algorithms, such as primality testing, random number generation and load balancing, utilize prime numbers to yield a more accurate and speedy result.
In short, prime numbers help computers:
- In a nutshel,l prime numbers can help computers:
- Secure your sensitive data
- Organize and safely store information
- Solving computational problems more efficiently
This is one of the reasons writing an efficient prime number program in Python is important. It gives you the experience of problem-solving while creating a framework for other advanced and complex topics in computer science such as cryptography and optimization of algorithms.
Overview of Methods to Check Prime Numbers in Python
There are multiple ways in Python you can check whether a number is prime. It depends on the size of the number (its magnitude), the level of optimization you would like, and the resources you have available.
Basic Methods
Basic methods involve straightforward approaches using loops and conditions. These basic methods are simple to implement and understand, but are not the best option for large numbers.
Optimized Methods
Optimized methods are aimed at minimizing iterations for checking primality. These methods indicate that a number could be prime, but involve some high-level math, using methods such as square root adjustments and skipping even number checks.
Advanced Methods
Advanced methods include recursion, the math module, partial prime tests (like Miller-Rabin), and all are very efficient in checking for primality, particularly for larger numbers.
Basic Methods to Check Prime Numbers
Using a Flag Variable
It is a simple method to check if a number is prime using a flag variable. This approach involves checking for repetition and division through all numbers up to the given number.
Code Example
def is_prime(n):
# Handle special cases (0, 1, and negative numbers)
if n <= 1:
return False
flag = True # Assume n is prime initially
# Check divisibility from 2 to sqrt(n)
for i in range(2, int(n**0.5) + 1): # range(2, sqrt(n)+1)
if n % i == 0: # modulo operator checks divisibility
flag = False
break # break statement exits early if divisor found
return flag
# Example usage
num = int(input("Enter a number: "))
print(f"{num} is prime: {is_prime(num)}")
Explanation
The program initially uses a flag variable to follow a number. This examines the partition from the square root of the number from 2. If a ruler is found, the flag is set on the False, indicating that the number is not prime. If no separator is found, the flag remains True, and the number is prime.
Output of the Program
Enter a number: 7 // input
7 is a prime number. // output
Using a For-Else Statement
A more "Pythonic" prime number program in Python uses the for-else construct. If a number is divisible by any number between 2 and n-1, the loop breaks and the else block is skipped. If the loop completes without finding a divisor, the else block executes, indicating the number is prime.
Python Code Implementation
def is_prime(n: int) -> bool:
if n <= 1:
return False # Not a prime number
# Loop to check divisibility from 2 to n-1
for i in range(2, n):
if n % i == 0:
return False # Not a prime number if divisible
return True # Prime number if no divisors found
# Input a number from the user
num = int(input("Enter a number: "))
# Check if the number is prime
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
Explanation
The for-else block provides a clean and concise implementation of this logic. It provides an elegant solution for a program for prime in Python. If no divisors were found, 1 will be returned, this indicates the number is prime.
Example Ouptut
Enter a number: 7 // input
7 is a prime number. // output
Optimized Methods to Check Prime Numbers
Optimization by Reducing Iterations to number/2 or √n
One of the most effective optimizations is reducing the range of iterations to sqrt(n). Since any factor of n greater than its square root must have a corresponding factor smaller than the square root, we can limit our checks.
Explanation of Logic and Working
- To check if a number √n is prime, we attempt to divide it by each integer starting from 2 up to √n. If √n is divisible by any of these integers, it is not a prime.
- If √n is divisible by some number larger than √n, the corresponding smaller factor would have already been found. Hence, checking divisibility only up to √n is enough to verify primality.
- This optimization reduces the number of divisions performed, making the algorithm much faster, especially for large numbers.
Python Code Implementation
import math
def is_prime(n):
# Edge cases for numbers less than 2
if n <= 1:
return False
# Check divisibility up to sqrt(n)
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
# Example of usage
number = 29
if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
Example Output
29 is a prime number.
Skipping Even Iterations for Efficiency
In addition to decreasing the number of iterations by checking divisibility, up to √n, another way to optimize the primality test is to skip even numbers altogether after doing the divisibility test for 2. That is, no even number greater than 2 is prime since all even numbers are divisible by 2; thus, we can eliminate them from testing, enhancing efficiency.
Explanation of Logic and Working
- Before entering the loop, we first check if the number nn is divisible by 2. If it is, and n>2n>2, we immediately return False, since any even number greater than 2 is not prime.
- After checking divisibility by 2, we can skip all even numbers in the iteration process, starting from 3. We can increment the loop variable by 2, ensuring that only odd numbers are tested for divisibility.
- By skipping even numbers, we reduce the number of iterations in half, making the primality test faster, especially for large numbers.
Python Code Implementation
import math
def is_prime(n):
# Edge cases for numbers less than 2
if n <= 1:
return False
# Check divisibility by 2 first
if n == 2:
return True
if n % 2 == 0:
return False
# Check divisibility from 3 to sqrt(n), skipping even numbers
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
# Example of usage
number = 29
if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
Example Output
29 is a prime number.
Advanced Methods for Checking Prime Numbers
For primitive testing for more advanced or alternative approaches, recurrence provides a useful technique. Recurring methods can sometimes simplify the logic of primality tests by breaking the problem into small, manageable parts.
Using Recursion
Repetition can be used to check whether a number is prime by repeatedly dividing the number and checking its division with small integer. Instead of using loops, the function itself tests the divisibility, making the code more elegant in some cases.
Python Code Implementation
import math
def is_prime_recursive(n, divisor=2):
# Base cases
if n <= 1:
return False
if divisor > math.sqrt(n):
return True
# Check divisibility by the current divisor
if n % divisor == 0:
return False
# Recursive call with next divisor
return is_prime_recursive(n, divisor + 1)
# Example of usage
number = 29
if is_prime_recursive(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
Example Output
29 is a prime number.
Explanation
The is_prime function tests whether number n is prime. It initially checks the numbers n \<= 1. It then checks for divisibility from 2 and onwards up to the square root of n. If it does not find any divisors, it will output True. If it does, it will output False.
Using the math Module
The Python math module contains mathematical functions to simplify prime number checking. An important function is math.sqrt(), which finds the square root of a number to optimize primality tests.
Explanation of the sqrt Function
The math.sqrt(n) function returns the square root of a given number √n. In the context of checking for prime numbers, we use this function to limit our divisibility checks up to √n, since any divisor greater than nn would have a corresponding smaller divisor already detected below √n. This optimization significantly reduces the number of iterations required in primality testing.
Python Code Implementation
import math
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
# Example usage
number = 29
if is_prime(number):
print(f"{number} is prime.")
else:
print(f"{number} is not prime.")
Example Output
29 is prime.
Explanation
The code above defines the function is_prime that checks whether a given number, N, is prime. It first returns False when the number is less than or equal to 1, as no number is prime. Then, it checks from N divided by the square root of N down to 2 for divisibility. If a divisor is found, N is not prime, and the function returns False. If no divisors are found, the function then returns to True, indicating N is prime. In the example, the function will check if the number 29 is prime and print is_prime is True, which means the number 29 is prime.
Using the sympy.isprime function in python
The isprime function in Python is used to check whether the number is prime or not. A sympy library is used, which provides a straightforward function known as sympy.isprime(). This is a powerful tool, especially for large numbers, as it is optimized and handles a variety of edge cases and special number types.
Introduction to the SymPy Library
SymPy is a Python package for symbolic mathematics. It includes methods for arithmetic, algebra, calculus, and number theory, among others. The isprime() function, part of this library, presents a very efficient way to determine whether a number is prime. Very well optimized for large integers, this method is a great choice for high-performance primality testing.
To use sympy, you'll need to install it via pip:
pip install sympy
Python Code Implementation
import sympy
def check_prime(n):
# Use the sympy isprime() function to check primality
if sympy.isprime(n):
return f"{n} is a prime number."
else:
return f"{n} is not a prime number."
# Example usage
num = int(input("Enter a number: "))
print(check_prime(num))
Example Output
Enter a number: 17
17 is a prime number.
Explanation
- The sympy library is imported to access the isprime() function.
- This function calls sympy.isprime(n) to check if the number is prime and returns the corresponding message.
- The user is asked to enter a number, and the check_prime() function is used to determine if the number is prime.
Using the Miller-Rabin Primality Test
The Miller-Rabin test is a probabilistic algorithm used for primality testing. While it can sometimes give a false positive (i.e., an incorrect determination of primality), it is highly efficient and accurate for large numbers when run multiple times.
Overview of the Algorithm
The Miller-Rabin primality test works by testing whether a number n behaves like a prime in a mathematical sense, based on certain conditions derived from modular arithmetic. It performs checks using different random bases to reduce the likelihood of false positives. The more times it is repeated with different bases, the more confident we can be in the result.
Python Code Implementation
import random
def miller_rabin(n, k=5):
# Edge cases for numbers less than 2
if n <= 1:
return False
if n == 2 or n == 3:
return True
# Write n-1 as 2^r * d
r, d = 0, n - 1
while d % 2 == 0:
r += 1
d //= 2
# Perform k rounds of testing
for _ in range(k):
a = random.randint(2, n - 2)
x = pow(a, d, n)
if x == 1 or x == n - 1:
continue
for _ in range(r - 1):
x = pow(x, 2, n)
if x == n - 1:
break
else:
return False
return True
# Example usage
number = 29
if miller_rabin(number):
print(f"{number} is prime.")
else:
print(f"{number} is not prime.")
Example Output
29 is prime.
Quick Recap:
Prime numbers can be verified via several approaches depending on your intentions and performance demands.
- Basic approaches (like using a flag variable) are most useful for simply being introduced to and understanding loops.
- Optimized approaches (like checking for number until √n and skipping even numbers) are for checking larger inputs and or improving efficiency.
- Advanced approaches, like the Sieve of Eratosthenes, are best for generating many primes as quickly as possible.
In short, the more sophisticated the logic, the faster the prime detection, ranging from simple loops to powerful sieves.
Generating Prime Numbers in Python
One of the common tasks that can be handled efficiently through number theory is the generation of prime numbers. There are different ways in which Python can be used to achieve that goal, such as finding all the primes within a range or getting the first n primes.
Generate Prime Numbers in a Range
To print prime numbers in a given range, we can use a simple loop or even a generator function.
Python Code Implementation
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def generate_primes_in_range(start, end):
primes = []
for num in range(start, end + 1):
if is_prime(num):
primes.append(num)
return primes
# Example usage
start = 10
end = 50
primes_in_range = generate_primes_in_range(start, end)
print(f"Prime numbers between {start} and {end}: {primes_in_range}")
Example Output
Prime numbers between 10 and 50: [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Python Code Using a Generator Function
A generator function can be used to yield prime numbers one by one in a range, making it more memory efficient for large ranges.
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def generate_primes_in_range(start, end):
for num in range(start, end + 1):
if is_prime(num):
yield num
# Example usage
start = 10
end = 50
primes_gen = generate_primes_in_range(start, end)
print("Prime numbers between 10 and 50:")
for prime in primes_gen:
print(prime, end=" ")
Example Output
Prime numbers between 10 and 50:
11 13 17 19 23 29 31 37 41 43 47
Generate the First n Prime Numbers
A common method to find all the prime numbers within a certain range is to use loops or generators.
Python Code Implementation
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def generate_first_n_primes(n):
primes = []
num = 2
while len(primes) < n:
if is_prime(num):
primes.append(num)
num += 1
return primes
# Example usage
n = 10
first_n_primes = generate_first_n_primes(n)
print(f"The first {n} prime numbers are: {first_n_primes}")
Example Output
The initial 10 prime numbers are: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29].
When writing a program in Python to determine whether or not a number is prime, it is critical to have a good approach to user input. This will keep your program running smoothly in the case of unexpected or incorrect user input. A good approach to input extends from prompting the user, to converting that input to the appropriate type, to validating that input, and optionally displaying any helpful error messages.
How to Handle User Input
- Prompting the User
- Provide a clear prompting message for the user.
- Converting Input
- Use input() to get the user's reply as a string.
- Use int() to convert that string to an integer .
- Validating Input
- Determine whether or not the input is a valid integer.
- You may also wish to check to make sure the number is a valid integer from an acceptable range (prime checks would need a number greater than 1), or fulfill whatever criteria you want your program to have.
- Handling Errors
- Use a try...except to catch conversion errors.
- If the user's input was not valid, inform the user that their input was invalid and prompt them to try again.
Example: User Input Handling
while True:
user_input = input("Enter a positive integer to check if it's prime: ")
try:
num = int(user_input)
if num <= 0:
print("Please enter a positive integer greater than zero.")
continue
break
except ValueError:
print("Invalid input. Please enter a valid integer.")
Key Points:
- The while loop ensures the user is repeatedly prompted until valid input is received.
- The try...except block catches cases where the input can't be converted to an integer.
- The program provides clear, actionable error messages.
Code Optimization Techniques for Prime Number Checking
Optimizing your code for checking prime numbers is important for improving performance, especially with larger inputs or repeated executions. Multiple strategies can be employed that reduce much of the unnecessary work being done to enhance the efficiency of your code.
Key Optimization Strategies
- Limiting Checks Up to the Square Root (√n)
- Instead of checking divisibility up to n-1, only check up to the integer value of the square root of n.
- If a number n is divisible by any number greater than its square root, the corresponding smaller factor would have already been found below the square root.
- Example:
import math
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
- Using Break Conditions
- Once a divisor is identified, exit the loop early with break or return – there's no need to continue checking since we've established it's composite.
- Example:
def is_prime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
- Reducing the Range of Numbers (n/2 Iterations)
- For numbers greater than 2, you can check divisibility only up to n/2, since any factor above n/2 would require a corresponding factor below n/2.
- However, checking up to √n is more efficient.
- Example:
def is_prime(n):
if n <= 1:
return False
for i in range(2, (n // 2) + 1):
if n % i == 0:
return False
return True
- Skipping Even Iterations
- After checking for divisibility by 2, iterate only through odd numbers, as even numbers (other than 2) cannot be prime.
- This reduces the number of iterations by about half.
- Example:
import math
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
When to Use Each Optimization
- Square root check (√n): Best for most situations; balances simplicity and efficiency.
- Break condition: Always use to avoid unnecessary checks.
- n/2 range: Less efficient than √n but better than checking up to n-1.
- Skipping even iterations: Combine with √n check for best performance on large numbers.
Applications of Prime Numbers
Prime numbers are more than just mathematical curiosities — they form the foundation of modern computing, cybersecurity, and number theory. Primes have such unique characteristics that may make them useful in solving problems in the real world. Below is a list of the most notable usages of prime numbers:
1. Cryptography and Encryption
In public-key cryptography, prime numbers are essential for algorithms like RSA and Diffie-Hellman. A prime number's property of being indivisible makes using them for key generation secure, since the only way to successfully generate the key later would be to factor the product of large primes, which is computationally challenging. Secure finance transactions, secure text messaging, and digital wallets, for example, all rely on prime numbers to cryptographically protect their sensitive information.
2. Random Number Generation
Primes are also used in random number generators to produce random sequences that are unpredictable. They prevent repeat cycles in the sequence, thus adding to the security. Random number generators are utilized, for instance, in machine learning algorithms that need a mathematically robust and unpredictable random number, simulations, gaming, and the creation of cryptographic keys.
3. Hash Functions and Data Structures
Prime numbers are also used in hash functions, which are used for data storage, indexing, and load balancing in systems. Using prime numbers in hash functions help to reduce collisions while increasing the efficiency of the algorithm and speed of data retrieval. For example, prime number hashing is used in databases, to ensure the integrity of blockchain technology, and improve search time performance in computer systems.
4. Computer Security and Key Generation
Primes can enable authentication, digital signatures, and key generation in protocols like SSL/TLS and ECC. Large prime numbers provide the foundation for secure communication, for protecting identities, and for resisting cyber threats. They are the basis for most modern cryptography and offer specific device defenses.
5. Error Detection and Coding Theory
Primes help with error detection, correction, and coding theory. We have seen how checksums, cyclic redundancy checks (CRCs), and compression algorithms use primes to detect and counteract errors in data transmission. Primes increase reliability in storing or receiving data.
6. Pure Mathematics and Research
Primes are an important area of number theory. They are used to prove theorems and conjectures around the Riemann Hypothesis. Their distribution and factorization patterns are studied for mathematical research, computational challenges, and advanced problem-solving in science and engineering.
Testing a number for primality can be done in different ways, each having its own characteristic performance. These methods mainly vary in their time complexity, efficiency, and the kind of problems they are used for.
Comparing Time Complexity of Methods
Each method of primality testing can be analyzed in terms of its time complexity, which is critical for understanding how it scales with large numbers.
1. Basic Methods
| Method |
Time Complexity |
Description |
| 1. Trial Division |
O(√n) |
Checks all numbers from 2 to n-1 to see if any divide n evenly. Simple but inefficient for large numbers. |
| 2. Trial Division up to √n |
O(√n) |
Optimizes by checking divisibility only up to √n, reducing the number of checks significantly. |
2. Optimized Techniques
| Method |
Time Complexity |
Description |
| 3. Skipping Even Numbers |
O(√n / 2) |
Skips even numbers after checking divisibility by 2, halving the number of checks by only checking odd numbers from 3 onward. |
| 4. Sieve of Eratosthenes |
O(n log(log n)) |
A faster method to generate a list of primes up to a given limit. Much quicker than trial division for bulk prime generation. |
3. Advanced Algorithms
| Method |
Time Complexity |
Description |
| 5. Miller-Rabin Primality Test |
O(k log3 n) for k iterations |
A probabilistic algorithm that checks if a number is prime with high confidence, but may give false positives (can reduce by increasing iterations). |
| 6. AKS Primality Test |
O(n7.5) |
A deterministic algorithm that runs in polynomial time. While theoretically optimal for large numbers, it is rarely used due to high complexity. |
Pros and Cons of Each Approach
| Method |
Pros |
Cons |
When to Use |
| 1. Trial Division |
Simple, easy to implement |
Very slow for large numbers |
Use for small numbers or when simplicity is more important than performance. |
| 2. Trial Division up to √n |
More efficient than basic trial division, easy to implement |
Still inefficient for large numbers |
Use for numbers up to moderate size where performance is important but not crucial. |
| 3. Skipping Even Numbers |
Further optimizes trial division by reducing the number of checks |
Still not efficient enough for large-scale applications |
Use when working with moderately large numbers, especially when implementing your own primality test. |
| 4. Sieve of Eratosthenes |
Extremely fast for generating a list of primes up to a limit |
Requires memory proportional to the range being checked, inefficient for very large ranges |
Use when you need a list of primes up to a large number, such as for cryptographic algorithms or other applications that require many primes. |
| 5. Miller-Rabin Primality Test |
Very fast, especially for large numbers, probabilistic approach gives quick results |
Can give false positives, though the likelihood is very low with enough iterations |
Use for very large numbers where speed is critical, and a small risk of error is acceptable. |
| 6. AKS Primality Test |
Deterministic and optimal for large numbers, polynomial time complexity |
Very slow in practice due to its high complexity, rarely used in real-world applications |
Use when an exact and deterministic primality test is needed, and performance is less important than absolute accuracy. |
Conclusion
Prime numbers are significant in a variety of areas in mathematics and computer science. Knowing how to efficiently check for a prime number in Python is an important Primes are not just terms used in mathematics; they are the foundation of encryption, hashing, algorithms, and data security. Learning how to write a Python Program to check Prime Number will promote logical thinking, will optimize your code, and will set a solid foundation for solving problems.
You have learned basic ways of checking for primes (e.g., using a flag variable), optimized techniques (like checking divisibility only up to √n), and advanced algorithms (e.g., the Sieve of Eratosthenes). You now will have several modes of validating whether an integer is prime or not with Python.
Points to remember:
- A prime number is one that can only be divided by 1 and itself, without leaving a remainder.
- Python has many ways to test for prime numbers, from simple beginner loops to advanced mathematic logic.
- The correct approach will depend on what you are using the method for:
- Single check - simplistic or optimized
- Multiple prime generation - Sieve of Eratosthenes
Why it Matters:
In modern applications like cryptography, cyber security systems, and blockchain algorithms, prime numbers are extensively used.
Knowing how to build a Python Program to Check Prime Number helps you work on real-world problems, not just classroom exercises.
Gain Practical Industry Skills in College to Land Your Dream in the IT Sector!
Explore ProgramFrequently Asked Questions
1. How to check if a number is prime in Python?
You can use the built-in isprime() function from the sympy library, or implement your methods using loops and optimizations like checking divisibility up to sqrt(n).
2. What is the isprime function in Python?
The isprime function in Python is available in the sympy library and efficiently checks if a number is prime.
3. How do I check if a number is prime using Python code?
Use simple methods like checking divisibility up to n-1 or optimized techniques like the square root method.
4. What is the most efficient way to check if a number is prime in Python?
The most efficient way is to use optimizations like reducing iterations to the square root of the number and skipping even numbers. For large numbers, you can use probabilistic tests like the Miller-Rabin test.
5. How do I check for prime numbers in Python using recursion?
You can implement a recursive function to check if a number is prime by dividing it by integers starting from 2. If no divisor is found, the number is prime.