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

โปรแกรมคำนวณค่า nCr ใน C++


ให้ n C r โดย C แทน combination n แทนจำนวนทั้งหมด r แทนการเลือกจากเซต งานคือคำนวณค่า nCr

Combination คือการเลือกข้อมูลจากเซตที่กำหนดโดยไม่สนใจลำดับ Permutation และ Combination ต่างกันที่ Permutation คือการจัดเรียง ส่วน Combination คือการเลือก

สูตร Permutation คือ -:

nPr = (n!)/(r!*(n-r)!)

ตัวอย่าง

Input-: n=12 r=4 Output-: value of 12c4 is :495

อัลกอริทึม

Start Step 1 -> Declare function for calculating factorial   int cal_n(int n)     int temp = 1     Loop for int i = 2 and i <= n and i++       Set temp = temp * i     End     return temp step 2 -> declare function to calculate ncr   int nCr(int n, int r)     return cal_n(n) / (cal_n(r) * cal_n(n - r)) step 3 -> In main()   declare variable as int n = 12, r = 4   print nCr(n, r) Stop

ตัวอย่าง

#include <bits/stdc++.h> using namespace std; //it will calculate factorial for n int cal_n(int n){   int temp = 1;   for (int i = 2; i <= n; i++)     temp = temp * i;   return temp; } //function to calculate ncr int nCr(int n, int r){   return cal_n(n) / (cal_n(r) * cal_n(n - r)); } int main(){   int n = 12, r = 4;   cout <<"value of "<<n<<"c"<<r<<" is : "<<nCr(n, r);   return 0; }

ผลลัพธ์

value of 12c4 is :495