Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C คำนวณ Permutation nPr

Permutation nPr = n! / (n-r)! : จำนวนวิธีจัดเรียง r รายการจาก n รายการ

ตัวอย่าง

5P2 = 5! / 3! = 120 / 6 = 20

โค้ดตัวอย่าง

#include <stdio.h>

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

long long nPr(int n, int r) {
    return fact(n) / fact(n - r);
}

int main() {
    int n = 5, r = 2;
    printf("%dP%d = %lld\n", n, r, nPr(n, r));
    return 0;
}

ผลลัพธ์

5P2 = 20