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

โปรแกรม C คำนวณค่า nPr (Permutation)


Permutation สัญลักษณ์ nPr หรือ P(n,r) เป็นสูตรคณิตศาสตร์หาจำนวนวิธีการเรียงสับเปลี่ยน สูตรคือ n! / (n - r)! จำนวน Permutation ของเซต n องค์ประกอบ คือ n! โดย ! แทนแฟกทอเรียล

Input: n=5; r=4; Output: 120

คำอธิบาย

P(5, 4) = 5! / (5-4)! => 120 / 1 = 120
5! = 1*2*3*4*5 = 120

ตัวอย่าง

#include <iostream>
using namespace std;
long int fact(int x) {
    int i, f = 1;
    for(i = 2; i <= x; i++) {
        f = f * i;
    }
    return f;
}
int main() {
    int n, r;
    long int npr;
    n = 5;
    r = 4;
    npr = fact(n) / fact(n - r);
    printf("%d", npr);
}