Skip to content
doubtly

2 answers

Best answer

Answer: Use a factorial function: \( ^nP_r = \frac{n!}{(n-r)!} \) and \( ^nC_r = \frac{n!}{r!\,(n-r)!} \).

Logic: a function fact() returns n! using a loop. The program checks 0 ≤ r ≤ n and then applies the two formulas.

Program:

#include <stdio.h>

long fact(int n)
{
    long f = 1;
    int i;
    for (i = 2; i <= n; i++)
        f = f * i;
    return f;
}

int main()
{
    int n, r;
    long npr, ncr;

    printf("Enter n and r: ");
    scanf("%d %d", &n, &r);

    if (n < 0 || r < 0 || r > n)
    {
        printf("Invalid input: need 0 <= r <= n\n");
        return 0;
    }

    npr = fact(n) / fact(n - r);
    ncr = fact(n) / (fact(r) * fact(n - r));

    printf("%dP%d = %ld\n", n, r, npr);
    printf("%dC%d = %ld\n", n, r, ncr);

    return 0;
}

Sample output (actual run):

Enter n and r: 5 2
5P2 = 20
5C2 = 10

Check: \( ^5P_2 = 120/6 = 20 \), \( ^5C_2 = 120/(2 \times 6) = 10 \).

Doubtly · 23 Apr 2022 Report
Was this answer helpful?

Answer: compute factorials and use \(^nP_r = \dfrac{n!}{(n-r)!}\) and \(^nC_r = \dfrac{n!}{r!\,(n-r)!}\).

#include <stdio.h>

long long fact(int n) {
    long long f = 1;
    for (int i = 2; i <= n; i++)
        f = f * i;
    return f;
}

int main() {
    int n, r;
    printf("Enter n and r: ");
    scanf("%d %d", &n, &r);

    if (r < 0 || n < 0 || r > n) {
        printf("Invalid input: need 0 <= r <= n\n");
        return 0;
    }

    long long nPr = fact(n) / fact(n - r);
    long long nCr = fact(n) / (fact(r) * fact(n - r));

    printf("nPr = %lld\n", nPr);
    printf("nCr = %lld\n", nCr);
    return 0;
}

Explanation: the function fact() returns \(n!\) using a loop. long long is used because factorials grow very fast (20! is the largest that fits). For r > n the values are not defined, so the input is checked.

Sample run: n = 5, r = 2 gives nPr = 20 and nCr = 10.

Doubtly AI · 24 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.