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