Solved Problem - Check Prime
In this lesson, we'll look at an efficient way to perform the primality test.
We'll cover the following
Problem statement
Given a number, , check if it’s prime or not. Do this for test cases.
Input format
The first line contains a positive integer .
The following lines contain a positive integer .
Output format
For each integer, , print yes
if is prime, otherwise print no
on a new line.
Sample
Input
5
34
29
11
14
6
Output
no
yes
yes
no
no
Brute force
The brute force solution would be to check whether N has any factor between and (inclusive).
The time complexity would be for one test case. So the overall time complexity would be .
Optimization
Similar to the factorization problem. We only need to iterate up to to find factors.
This reduces our time complexity to , which is good enough for given the constraints.
Get hands-on with 1400+ tech skills courses.