Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Prime Factorization Tips and Tricks
Next article icon

Trial division Algorithm for Prime Factorization

Last Updated : 27 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, the trial division method to check whether a number is a prime or not is discussed. Given a number N, the task is to check whether the number is prime or not. 

Examples: 

Input: N = 433 
Output: Prime 
Explanation: 
The only factors of 433 are 1 and 433. Therefore, it is a prime. 

Input: N = 1263 
Output: Composite 
Explanation: 
The factors of 1263 are 1, 3, 421, 1263. Therefore, it is a composite number. 

Naive Approach: By definition, a prime number is a whole number greater than 1, which is only divisible by 1 and itself. Therefore, we initialize a loop from 2 to N – 1 and check the divisibility. The following is the pseudo-code for the approach:  

N <- input initialise: i <- 2 while(i ? N - 1):     if(N % i == 0):         return "Composite" return "Prime" 

Time Complexity Analysis: 

  • For any given number N, the while loop runs for N – 2 times. Therefore, the time complexity for the while loop is O(N).
  • The divisibility check is done in constant time. Therefore, the time complexity for the if condition in the while loop is O(1).
  • Therefore, the overall time complexity of the above approach is O(N).

Trial Division Method: The primality check can be performed more efficiently by the concept of the trial division method. The Trial Division method is one of the crucial but one of the easiest factorization techniques when dealing with integer factorization. 

Observation: The above method works with the observation that the maximum factor for any number N is always less than or equal to the square root(N). This conclusion can be derived in the following way: 

  • From the school arithmetics, it is a known fact that any composite number is built out of two or more prime numbers.
  • Let the factors of N be n1, n2, and so on. The factors are largest only when there exist two factors n1 and n2 for the number N.
  • Therefore, let’s assume n1 and n2 are the two largest factors for the number N. These numbers n1 and n2 can be largest only when both n1 and n2 are equal.
  • Let n1 = n2 = n. Therefore, N = n * n. Hence, the largest possible factor for N is square root(N).

Approach: From the above observation, the approach for this algorithm is straightforward. The idea is instead of checking till N – 1 for a factor, we only check until square root(N). 

Below is the implementation of the above approach:  

C++




// CPP implementation of
// Trial Division Algorithm
#include <bits/stdc++.h>
 
using namespace std;
 
// Function to check if a number is
// a prime number or not
int TrialDivision(int N){
 
    // Initializing with the value 2
    // from where the number is checked
    int i = 2;
 
    // Computing the square root of
    // the number N
    int k = ceil(sqrt(N));
 
    // While loop till the
    // square root of N
    while(i<= k){
 
        // If any of the numbers between
        // [2, sqrt(N)] is a factor of N
        // Then the number is composite
        if(N % i == 0)
            return 0;
        i += 1;
    }
 
    // If none of the numbers is a factor,
    // then it is a prime number
    return 1;
}
 
// Driver code
int main()
{
    int N = 49;
    int p = TrialDivision(N);
 
    // To check if a number is a prime or not
    if(p)
        cout << ("Prime");
    else
        cout << ("Composite");
 
    return 0;
}
 
// This code is contributed by mohit kumar 29
 
 

Java




// Java implementation of
// Trial Division Algorithm
import java.util.*;
  
class GFG{
   
// Function to check if a number is
// a prime number or not
static int TrialDivision(int N){
 
    // Initializing with the value 2
    // from where the number is checked
    int i = 2;
 
    // Computing the square root of
    // the number N
    int k =(int) Math.ceil(Math.sqrt(N));
 
    // While loop till the
    // square root of N
    while(i<= k){
 
        // If any of the numbers between
        // [2, sqrt(N)] is a factor of N
        // Then the number is composite
        if(N % i == 0)
            return 0;
        i += 1;
    }
 
    // If none of the numbers is a factor,
    // then it is a prime number
    return 1;
}
 
// Driver Code
public static void main(String[] args)
{
  
    int N = 49;
    int p = TrialDivision(N);
 
    // To check if a number is a prime or not
    if(p != 0)
        System.out.print("Prime");
    else
        System.out.print("Composite");
 
}
}
 
// This code is contributed by shivanisinghss2110
 
 

Python3




# Python3 implementation of
# Trial Division Algorithm
 
# Function to check if a number is
# a prime number or not
def TrialDivision(N):
 
    # Initializing with the value 2
    # from where the number is checked
    i = 2
 
    # Computing the square root of
    # the number N
    k = int(N ** 0.5)
 
    # While loop till the
    # square root of N
    while(i<= k):
 
        # If any of the numbers between
        # [2, sqrt(N)] is a factor of N
        # Then the number is composite
        if(N % i == 0):
            return 0
        i += 1
 
    # If none of the numbers is a factor,
    # then it is a prime number
    return 1
     
# Driver code
if __name__ == "__main__":
    N = 49
    p = TrialDivision(N)
 
# To check if a number is a prime or not
    if(p):
        print("Prime")
    else:
        print("Composite")
        
 
 

C#




// C# implementation of
// Trial Division Algorithm
using System;
 
class GFG{
 
// Function to check if a number is
// a prime number or not
static int TrialDivision(int N){
 
    // Initializing with the value 2
    // from where the number is checked
    int i = 2;
 
    // Computing the square root of
    // the number N
    int k =(int) Math.Ceiling(Math.Sqrt(N));
 
    // While loop till the
    // square root of N
    while(i<= k){
 
        // If any of the numbers between
        // [2, sqrt(N)] is a factor of N
        // Then the number is composite
        if(N % i == 0)
            return 0;
        i += 1;
    }
 
    // If none of the numbers is a factor,
    // then it is a prime number
    return 1;
}
 
// Driver Code
public static void Main()
{
 
    int N = 49;
    int p = TrialDivision(N);
 
    // To check if a number is a prime or not
    if(p != 0)
        Console.Write("Prime");
    else
        Console.Write("Composite");
 
}
}
 
// This code is contributed by AbhiThakur
 
 

Javascript




<script>
 
// JavaScript implementation of
// Trial Division Algorithm
 
 
// Function to check if a number is
// a prime number or not
function TrialDivision(N){
 
    // Initializing with the value 2
    // from where the number is checked
    let i = 2;
 
    // Computing the square root of
    // the number N
    let k = Math.ceil(Math.sqrt(N));
 
    // While loop till the
    // square root of N
    while(i<= k){
 
        // If any of the numbers between
        // [2, sqrt(N)] is a factor of N
        // Then the number is composite
        if(N % i == 0)
            return 0;
        i += 1;
    }
 
    // If none of the numbers is a factor,
    // then it is a prime number
    return 1;
}
 
// Driver code
 
let N = 49;
let p = TrialDivision(N);
 
// To check if a number is a prime or not
if(p)
    document.write("Prime");
else
    document.write("Composite");
 
// This code is contributed by gfgking
 
</script>
 
 
Output: 
Composite

 

Time Complexity Analysis: 

  • The while loop is executed for a maximum of square root(N) times. Therefore, the time complexity of the while loop is O(sqrt(N)).
  • The running time of all the if conditions are constant. Therefore, the time complexity of the if statements are O(1).
  • Therefore, the overall time complexity is O(sqrt(N)).

Optimized Trial Division Method: The above trial division method can be further optimized by eliminating all even numbers in the range [2, K] where K = square root(N) as 2 is the only even prime number. The overall complexity still remains the same but the number of executions gets reduced by half.

Note: The optimization made in the Trial Division method might seem very small as this method is almost similar to Naive Approach except the number of iterations. However, this drastically reduces the number of computations for higher values of N. This is explained by the following graph plotted against the corresponding running times of the algorithms: 

 



Next Article
Prime Factorization Tips and Tricks

V

vanshikagoyal43
Improve
Article Tags :
  • Algorithms
  • DSA
  • Mathematical
  • Prime Number
Practice Tags :
  • Algorithms
  • Mathematical
  • Prime Number

Similar Reads

  • Pollard's Rho Algorithm for Prime Factorization
    Given a positive integer n, and that it is composite, find a divisor of it.Example: Input: n = 12;Output: 2 [OR 3 OR 4]Input: n = 187;Output: 11 [OR 17]Brute approach: Test all integers less than n until a divisor is found. Improvisation: Test all integers less than ?nA large enough number will stil
    14 min read
  • Real Life Applications of Prime Factorization
    Prime factorization has applications from securing online transactions to optimizing computer algorithms and even decoding secret messages, prime factorization plays a vital role in various aspects of modern technology and beyond. Applications of Prime FactorizationSome real-life applications of pri
    9 min read
  • Mathematical Algorithms - Prime Factorization and Divisors
    In the Mathematical algorithm there are two fundamental mathematical algorithms that is prime factorization and finding divisors. Prime factorization is the process of breaking down a number into its prime factors, while finding divisors involves identifying all the numbers that can evenly divide th
    3 min read
  • Prime Factorization Tips and Tricks
    Let us first go through the standard Prime Factorization by Division Method. Then we will be talking about tips and tricks to make it faster. Step 1: Divide the number by the smallest prime number (i.e. 2) until we are able to divide the given number without leaving any remainder. Step 2: Move on to
    2 min read
  • Factorization of Algebraic Expression
    In algebra, factorization is a fundamental concept that helps in simplifying expressions and solving equations. Factorization involves breaking down algebraic expressions into simpler components, which aids in understanding their structure and properties. In this article, we'll look at basic methods
    7 min read
  • Generating all divisors of a number using its prime factorization
    Given an integer N, the task is to find all of its divisors using its prime factorization. Examples: Input: N = 6 Output: 1 2 3 6 Input: N = 10 Output: 1 2 5 10 Approach: As every number greater than 1 can be represented in its prime factorization as p1a1*p2a2*......*pkak, where pi is a prime number
    7 min read
  • Interesting Facts about Prime Factorization
    1. Every integer greater than 1 can be uniquely factored into prime numbers. This is known as the Fundamental Theorem of Arithmetic. For example, 60 can be written as 22×3×5 and no other set of prime numbers can multiply to give 60. 2. The RSA Algorithm is said to secure 90% of the Internet. When yo
    3 min read
  • Prime Factorization
    Prime Factorization is a way of writing numbers as the product of prime numbers. Prime numbers are natural numbers that have only two divisors, 1 and themselves. Prime Factorization involves only the prime numbers as every composite number can be written as the product of primes. Let’s understand th
    10 min read
  • Distinct Prime Factors of Array Product
    Given an array of integers. Let us say P is the product of elements of the array. Find the number of distinct prime factors of product P. Examples: Input : 1 2 3 4 5 Output : 3 Explanation: Here P = 1 * 2 * 3 * 4 * 5 = 120. Distinct prime divisors of 120 are 2, 3 and 5. So, the output is 3. Input :
    7 min read
  • Count of distinct power of prime factor of N
    Given a positive integer N, the task is to find the total number of distinct power of prime factor of the given number N.Examples: Input: N = 216 Output: 4 Explanation: 216 can be expressed as 2 * 22 * 3 * 32. The factors satisfying the conditions are 2, 22, 3 and 32 as all of them are written as di
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences