Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find if nCr is divisible by the given prime in C++
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)!
Example
#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";
else
cout << "nCr is not divisible by P";
}
Output
nCr is divisible by P
Advertisements