Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

HELP! I\'m writing a C program for calculating Permutations and Combinations. Wh

ID: 3589407 • Letter: H

Question

HELP! I'm writing a C program for calculating Permutations and Combinations. When I enter n=5 and r=2 it gives me the correct value. But when I enter n=52 and r=5 the difference for both the Permutation and Combination is 1. nPr=311875199 (instead of 311875200) and nCr=2598959 (instead of 2598960). Also when n is bigger than r it gives me negative values (ex: n=100 and r=5). Is there any way to get the correct value for any two numbers and not just some numbers? This is what I have as my C program:

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

#include <stdio.h>
#include <conio.h>

int main()
{
int n,r,ncr(int,int);
long npr(int,int);
long double fact(int);
printf("Enter the value of n:");
scanf("%d",&n);
printf("Enter the value of r:");
scanf("%d",&r);

if(n>=r){
printf("%dC%d is: %d ",n,r,ncr(n,r));
printf("%dP%d is: %d ",n,r,npr(n,r));
} else{
printf("WRONG INPUT, n>=r");
}
}
long double fact(int p){
long double facts=1;
int i;
for(i=1;i<=p;i++)
facts=facts*i;
return(facts);
}
int ncr(int n, int r){
return (fact(n)/(fact(r)*fact(n-r)));
}
long npr(int n, int r){
return(fact(n)/fact(n-r));
}

Explanation / Answer

#include <stdio.h>
long int factorial (long int x);

int main ()
{
    long int n,r;
    long int ncr,npr;
    printf ("Enter value of n:");
    scanf ("%ld",&n);
    printf ("Enter value of r:");
    scanf ("%ld",&r);
    npr = factorial(n)/factorial(n-r);
    ncr = npr / factorial(r);
    printf ("npr value is:%ld ",npr);
    printf ("ncr value is:%ld ",ncr);
   
    return 0;
}

/* Function to calculate factorial */
long int factorial (long int x)
{
    int i,f=1;
    for (i=2 ; i<=x ; i++)
        f = f * i;
    return (f);
}