Find if nCr is divisible by the given prime in C++

C++Server Side ProgrammingProgramming

Suppose there are three variables N, R and P. The N and R are used to get the NCR and P is a prime. We have to find whether NCR is divisible by P. Suppose we have some numbers N = 7, R = 2 and P = 3, then 7C2 = 21, this is divisible by 3, so the output will be true.

We know that NCR = N! / (R! * (N – R)! ). We will use Legendre Formula to largest power of P, which divides any N!, R! and (N – R)! in order to NCR to be divisible by P, the condition is N! > R! + (N - R)!


 Live Demo

#include <iostream>
using namespace std;
int getPower(int n, int p) {
   int pow = 0;
   while (n) {
      n /= p;
      pow += n;
   return pow;
bool isDivisibleByP(int n, int r, int p) {
   // Find the highest powers of p
   // that divide n!, r! and (n - r)!
   int x1 = getPower(n, p);
   int x2 = getPower(r, p);
   int x3 = getPower(n - r, p);
   if (x1 > x2 + x3)
   return true;
   return false;
int main() {
   int n = 7, r = 2, p = 7;
   if (isDivisibleByP(n, r, p))
      cout << "nCr is divisible by P";
      cout << "nCr is not divisible by P";


nCr is divisible by P
Updated on 21-Oct-2019 07:52:50