Given three integers N, R and P where P is prime, the task is to find whether NCR is divisible by P or not.
Examples:
Input: N = 6, R = 2, P = 7
Output: No
6C2 = 15 which is not divisible by 7.
Input: N = 7, R = 2, P = 3
Output: Yes
7C2 = 21 which is divisible by 3.
Approach: We know that NCR = N! / (R! * (N – R)!). Now using Legendre Formula, find the largest power of P which divides any N!, R! and (N -R)! say x1, x2 and x3 respectively.
In order for NCR to be divisible by P, the condition x1 > x2 + x3 must be satisfied.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int getfactor( int n, int p)
{
int pw = 0;
while (n) {
n /= p;
pw += n;
}
return pw;
}
bool isDivisible( int n, int r, int p)
{
int x1 = getfactor(n, p);
int x2 = getfactor(r, p);
int x3 = getfactor(n - r, p);
if (x1 > x2 + x3)
return true ;
return false ;
}
int main()
{
int n = 7, r = 2, p = 7;
if (isDivisible(n, r, p))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int getfactor( int n, int p)
{
int pw = 0 ;
while (n != 0 )
{
n /= p;
pw += n;
}
return pw;
}
static int isDivisible( int n, int r, int p)
{
int x1 = getfactor(n, p);
int x2 = getfactor(r, p);
int x3 = getfactor(n - r, p);
if (x1 > x2 + x3)
return 1 ;
return 0 ;
}
public static void main (String[] args)
{
int n = 7 , r = 2 , p = 7 ;
if (isDivisible(n, r, p) == 1 )
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
def getfactor(n, p) :
pw = 0 ;
while (n) :
n / / = p;
pw + = n;
return pw;
def isDivisible(n, r, p) :
x1 = getfactor(n, p);
x2 = getfactor(r, p);
x3 = getfactor(n - r, p);
if (x1 > x2 + x3) :
return True ;
return False ;
if __name__ = = "__main__" :
n = 7 ; r = 2 ; p = 7 ;
if (isDivisible(n, r, p)) :
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG
{
static int getfactor( int n, int p)
{
int pw = 0;
while (n != 0)
{
n /= p;
pw += n;
}
return pw;
}
static int isDivisible( int n, int r, int p)
{
int x1 = getfactor(n, p);
int x2 = getfactor(r, p);
int x3 = getfactor(n - r, p);
if (x1 > x2 + x3)
return 1;
return 0;
}
static public void Main ()
{
int n = 7, r = 2, p = 7;
if (isDivisible(n, r, p) == 1)
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function getfactor(n, p)
{
let pw = 0;
while (n != 0)
{
n = parseInt(n / p, 10);
pw += n;
}
return pw;
}
function isDivisible(n, r, p)
{
let x1 = getfactor(n, p);
let x2 = getfactor(r, p);
let x3 = getfactor(n - r, p);
if (x1 > x2 + x3)
return 1;
return 0;
}
let n = 7, r = 2, p = 7;
if (isDivisible(n, r, p) == 1)
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(logpn)
Auxiliary Space: O(1)