C program to find nCr and nPr
C program to find nCr and nPr, remember, nCr = n!/(r!*(n-r)!) and nPr = n!/(n-r)!.
C program to find nPr and nCr using a function
#include <stdio.h>
#include <conio.h>
long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);
void main()
{
int n, r;
long ncr, npr;
printf("Enter the value of n and r\n");
scanf("%d%d",&n,&r);
ncr = find_ncr(n, r);
npr = find_npr(n, r);
printf("%dC%d = %ld\n", n, r, ncr);
printf("%dP%d = %ld\n", n, r, npr);
getch();
}
long find_ncr(int, int);
long find_npr(int, int);
void main()
{
int n, r;
long ncr, npr;
printf("Enter the value of n and r\n");
scanf("%d%d",&n,&r);
ncr = find_ncr(n, r);
npr = find_npr(n, r);
printf("%dC%d = %ld\n", n, r, ncr);
printf("%dP%d = %ld\n", n, r, npr);
getch();
}
long find_ncr(int n, int r) {
long result;
result = factorial(n)/(factorial(r)*factorial(n-r));
return result;
}
long find_npr(int n, int r) {
long result;
result = factorial(n)/factorial(n-r);
return result;
}
long factorial(int n) {
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
long result;
result = factorial(n)/(factorial(r)*factorial(n-r));
return result;
}
long find_npr(int n, int r) {
long result;
result = factorial(n)/factorial(n-r);
return result;
}
long factorial(int n) {
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
Output of program:
Another way to calculate nPr and nCr using functions
We use long long data type in our program to handle large numbers.
#include <stdio.h>
#include <conio.h>
#define ll long long
#define ll long long
void find_ncr_npr(int, int, ll*, ll*);
ll find_npr(int, int);
ll factorial(int);
ll find_npr(int, int);
ll factorial(int);
void main() {
int n, r;
ll ncr, npr;
int n, r;
ll ncr, npr;
printf("Input n and r\n");
scanf("%d%d", &n, &r);
scanf("%d%d", &n, &r);
find_ncr_npr(n, r, &npr, &ncr);
printf("%dC%d = %lld\n", n, r, ncr);
printf("%dP%d = %lld\n", n, r, npr);
printf("%dC%d = %lld\n", n, r, ncr);
printf("%dP%d = %lld\n", n, r, npr);
getch();
}
}
void find_ncr_npr(int n, int r, ll *npr, ll *ncr) {
*npr = find_npr(n, r);
*ncr = *npr/factorial(r);
}
*npr = find_npr(n, r);
*ncr = *npr/factorial(r);
}
ll find_npr(int n, int r) {
ll result = 1;
int c = 1;
ll result = 1;
int c = 1;
while (c <= r) {
result = result * (n - r + c);
c++;
}
return result;
}
result = result * (n - r + c);
c++;
}
return result;
}
ll factorial(int n) {
int c;
ll result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
int c;
ll result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
No comments:
Post a Comment