Trial division Algorithm for Prime Factorization

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 to 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 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, lets 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 straight forward. 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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")
         

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 codee is contributed by AbhiThakur

chevron_right


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, overall time complexity is O(sqrt(N)).

Optimised 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:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.