Skip to main content

Prime number testing | Numerical Algorithms


A prime number is a number that is only divisible by 1 and the number itself. There are multiple ways we could test if a number is prime or not but today we will talk about two ways-
  1. Naive method
  2. sqrt(n) prime testing (the efficient method)

The Naive method
One method would be to check all possibilities from 2 to n - 1, n being the number we are testing. This would mean that if a number is prime we will have to search through all the numbers from 2 to n - 1. But if a number is not a prime then we will not have to search through all the possibilities, we will just return false if a number is completely divisible by another number that means it doesn't leave any remainder.

def isPrime(n):
    for i in range(2,n):
        if n%i==0:
            return False
    return True
The worst case for this method would be O(N).
Sqrt(n) method
Okay, so the logic behind this method is that every composite number has at least one factor that lies between 0 and the square root of n. Thus, we only check if it has a factor and if it does indeed have a factor, it's not a prime.
import math

def isPrime(n):
    if n <= 1:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    m = int(math.sqrt(n))
    for i in range(3,m,2):
        if n % i == 0:
            return False
    return True
First we check if the number is equal to or less than one. Then we check if the number is to 2 and return True. Next, we check if a number is even, if it is even, then it's not a prime. Then in the last step we go through all the odd numbers between 3 and the square root of if a number is divisible by an even number then it will be divisible by 2 which we check for in the previous step, if any number completely divides n we return False, else we return True. This algorithm has a worst case run time of O(sqrt(n)), which is a huge improvement over the naive algorithm.

For more tutorials on algorithms and data structures, subscribe to this blog and also explore this blog for other interesting tutorials.

Comments

Popular Posts

Evaluating expressions using Stacks | Dijkstra's Two-Stack Algorithm

We are going to look at Dijkstra's two-stack algorithm and see how it's implemented. This algorithm is used to evaluate infix expressions. It uses stacks at its core, so if you don't know about stacks or if you'd want to learn more about them, click this link There are three types of expressions, Infix : Infix expressions are the ones where the operators are used between values, like a + b - c . Postfix : These are the expressions where operators are written after the values, like a b c +- , this translates to a + b - c in infix. Prefix : In these expressions, the operators are written before the values, for example + - a b c . This expression will also be equal to a + b - c in infix. Okay, so what this algorithm does is evaluate expressions like ( ( 3 + 4 ) * 83 ) . It starts by breaking down this expression into a list of stings and create two empty stack, one for housing the values and other for the operators. Then we go through the list one by one. Whenev...

Python for competitive programming

WHY USE PYTHON FOR COMPETITIVE CODING Well a very good reason is that python is a language which radically cuts short the time you spend writing code ,rather you could spend that time thinking about the logic that is needed for the question. In these kind of competitions speed is necessary,I am not talking about the speed of the language but rather about the speed of the programmer.Python syntax is extremely clutter free and elegant which allows us to not get tangled up in complicated details of a programming language. Python also has a very vast variety of tools in its standard library and these tools can be very well utilised in competitive programming. Here's a list of a whole lot of other reasons why you would want to use python: Common inbuilt functions: Python has common functions like count,min,max,sorted etc.These functions allow you to easily go ahead and skip writing code for these trivial procedures which often prove to be very helpful,rest assured: Pytho...

Lambda functions in Python

Lambda functions are simply functions that don't have a name. They are also called anonymous functions and are pretty useful for certain cases. They are extensively used in functional programming . Lambda expression is useful for creating small, one time use functions though the functions can also be given a name. It can have multiple arguments but just a single expression as the function body. The basic syntax to create a lambda function is lambda arguments: function body For example lambda x : x **2 This function takes in x and returns x 2 . Here, lambda is the keyword, x is the argument and the expression after the colon is the function body. These functions can also be given a name, sqr = lambda x : x **2 sqr(5) #output : 25 Multiple arguments can also be provided lambda x,y: x * y or lambda x,y,z: x*y*z These functions when given a name are equivalent to the functions defined by using the def keyword. For example def solve_quad(a,b,c): d = b**2 - (4*a*c) x1 ...

Balanced Brackets | Stacks

In this post we will explore and implement an algorithm which helps us verify that if the brackets are balanced or validly used. This is a very important application of stacks as a lot of programming languages use brackets very extensively in their syntax and one of the job of a compiler is to check if the brackets are balanced or not. For simplicity's sake we will just use a list with the methods append() and pop(). This will help us emulate a stack without actually needing to implement it. If you want to, you can go and learn about stacks on this link . A set of brackets can be called balanced if all of the brackets in it are properly matched. Examples of balanced brackets : (([]{}{})) ({{}}[]) Examples of unbalanced brackets : (([)]) {{}]}]]) So now getting to the algorithm, what we simply do is that we go through a string of brackets and check that for every closing bracket there is a properly nested opening bracket. This is how we do it - Convert the input string into a...

Tuple data structure in Python

Tuple is a linear data structure which more or less behaves like a python list but with a really important difference, that a tuple is immutable . Immutable means that this structure can't be changed after it has been created, it can't be mutated if I may. Tuples being immutable are more memory efficient than list as they don't over allocate memory . Okay, so what this means is, when a list is created it takes up and reserves extra spaces of memory than needed for the original elements as new elements might be added to the list later and allocating memory on every addition would be quite inneficient but tuples, once created surelly won't change the numbers of elements in it later on, so it allocates exactly how much memory is needed. Almost all the list operations work for tuples except the ones which mutate it, for example, insert, append, remove etc. Declaring a tuple : Tuples can be initialise in a manner similar to list, But there's an important c...

Fast Multiplication of Long Integeres | Karatsuba's Algorithm

This article is divided into 3 parts, so feel free to skip around to the part you find useful - Need for the algorithm Intuition and Algorithm Implementation Need for the algorithm Multiplication is an elementary concept known to all of us since a very early age. But multiplication of very large numbers becomes a difficult problem that can't be solved mentally unless you're a mathematical genius and hence we use calculators and computers. Computers too can efficiently multiply numbers but as the length of digits of the number increases, the time complexity also increases along with it quadratically. To calculate the product of humongous numbers we need a better algorithm. Any algorithm that even slightly increases the runtime will prove to be very beneficial for large values of n, say 100000. Karatsuba multiplication algorithm brings down the number of operations by a factor of one and gives a huge boost. Intuition and Algorithm Okay so, to boost up the speed of...

Divide and Conquer

Divide and Conquer Divide and Conquer is an algorithmic paradigm used in many problems and algorithms . Some of the most common algorithms use divide and conquer principle and are highly effective. A Divide and Conquer algorithm solves a problem in 3 steps : Divide: Break the given problem into subproblems of same type. Conquer: Recursively solve these subproblems Combine: Appropriately combine the answers It starts of by breaking down a problem into multiple parts that are simple enough to be solved and then all these subparts are solved individually. For the last part , the algorithm combines all the solutions into one. Some common examples of Divide and Conquer in algorithms are - Binary Search Merge Sort Quick Sort Divide and Conquer is the principle applied to recursion and thus it is a very important technique and is of immense use for programmers. Resources - Wikipedia Technical details

Greedy Algorithms

Greedy Algorithms is an algorithmic paradigm just like divide and conquer is. It is a design technique that depends on locally optimal choices to produce an overall optimal solution. It makes a greedy choice at every step based on a condition and hopes that the choice it made will produce the most optimum solution. A lot of times this technique fails to generate algorithms that are optimal but it does make a lot of problems very very easy. Its used in several different algorithms, most famous of them being: Huffman Coding Dijstrika's Shortest path Kruskal’s Minimum Spanning Tree Greedy algorithms basically make up a solution step by step fashion choosing the next piece which offers the most immediate benefit. Some problems based on Greedy Algorithms are - Grocery Bagger School Assembly Boxing Chopsticks Receipt

Project Ideas for Python

Project Ideas for Python Well , python is an extremely versatile language , several different types of projects can be made in python from Graphical user interfaces to Web apps. It being a language with a very extensive standard library has a lot of potential. Project Ideas: Web Development Using python frameworks like Django , Flask , Web2py etc ,a web application or a website can be developed very easily. But to make a project first you will have to learn the framework you choose. Frameworks : Flask - Flask Mega Tutorial Django - Video Tutorial Web2py - Tutorialspoint-Web2py Website Ideas : Notes app Blog To do list Voting App Twitter Clone (fairly complex) Games Python can be used to develop games using pygame . It is very simple to write games in python in pygame and really anyone with basic python skills can get a game up and running in a very short time. Game examples : Flappy Bird 2048 Tic-Tac-Toe Desktop GUI (Graphical User Interface...

Queue

Today, we will talk about another linear data structure , a Queue. It is a data structure thay basically acts like a real life queue. It works on FIFO (First in First out) principle. It means that the element that gets added to the queue first gets removed the first, it's like first come first serve basis.In a queue, the operations take effect at rear and front end of the list. Enque adds the element to the back of the queue and Dequeue removes the element from the front of the queue. Queue is a very essential data structure and also form the basis for some advanced data structures. Applications of a queue- CPU procces scheduling Real life simulations The methods associated with a queue are - Enque(): Adds an element to the back of the queue Deque(): Removes an element from the front of the queue isEmpty(): Returns wether the queue is empty or not size(): Returns the size of the queue Here is the implementation of the Queue data structure, in this implementation we...