Given a number N, find the smallest prime divisor of N.
Examples:
Input: 25
Output: 5
Input: 31
Output: 31
Approach:
- Check if the number is divisible by 2 or not.
- Iterate from i = 3 to sqrt(N) and making a jump of 2.
- If any of the numbers divide N then it is the smallest prime divisor.
- If none of them divide, then N is the answer.
Below is the implementation of the above algorithm:
C++
#include <bits/stdc++.h>
using namespace std;
int smallestDivisor( int n)
{
if (n % 2 == 0)
return 2;
for ( int i = 3; i * i <= n; i += 2) {
if (n % i == 0)
return i;
}
return n;
}
int main()
{
int n = 31;
cout << smallestDivisor(n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int smallestDivisor( int n)
{
if (n % 2 == 0 )
return 2 ;
for ( int i = 3 ; i * i <= n; i += 2 ) {
if (n % i == 0 )
return i;
}
return n;
}
public static void main (String[] args) {
int n = 31 ;
System.out.println (smallestDivisor(n));
}
}
|
Python3
def smallestDivisor(n):
if (n % 2 = = 0 ):
return 2 ;
i = 3 ;
while (i * i < = n):
if (n % i = = 0 ):
return i;
i + = 2 ;
return n;
n = 31 ;
print (smallestDivisor(n));
|
C#
using System;
class GFG
{
static int smallestDivisor( int n)
{
if (n % 2 == 0)
return 2;
for ( int i = 3;
i * i <= n; i += 2)
{
if (n % i == 0)
return i;
}
return n;
}
static public void Main ()
{
int n = 31;
Console.WriteLine(smallestDivisor(n));
}
}
|
PHP
<?php
function smallestDivisor( $n )
{
if ( $n % 2 == 0)
return 2;
for ( $i = 3; $i * $i <= $n ; $i += 2)
{
if ( $n % $i == 0)
return $i ;
}
return $n ;
}
$n = 31;
echo smallestDivisor( $n );
?>
|
Javascript
<script>
function smallestDivisor(n) {
if (n % 2 == 0)
return 2;
for ( var i = 3; i * i <= n; i += 2) {
if (n % i == 0)
return i;
}
return n;
}
var n = 31;
document.write(smallestDivisor(n));
</script>
|
Time Complexity: O(sqrt(N)), as we are using a loop to traverse sqrt (N) times. As the condition is i*i<=N, on application of sqrt function on both the sides we get sqrt (i*i) <= sqrt(N), which is i<= sqrt(N), therefore the loop will traverse for sqrt(N) times.
Auxiliary Space: O(1), as we are not using any extra space.