Permutation and combination algorithm (C language)

Preface
If you want to use C language to realize the calculation of permutation and combination, you must first know the calculation formula of permutation and combination.
Arrangement: A(n, m) = n! / (n - m)! (! is formed)
A(n, m) means selecting m elements from n elements for arrangement and
combination: C(n, m) = n! / (m! * (n - m)!)
C(n, m) means selecting m elements from n elements for combination.
After understanding these formulas, we can start our study today!
Insert image description here

Code implementation
arrangement:

#include<stdio.h>
long long factorial(long long n)//计算结成
{
    
    
	if (n == 0 || n == 1)
		return 1;
	else
		return n * factorial(n - 1);
}
long long permutation(long long n, long long m)//计算排列
{
    
    
	return factorial(n) / factorial(n - m);
}
int main()
{
    
    
	long long n, m;
	scanf("%lld %lld", &n, &m);//输入n和m
	long long  ans = permutation(n, m);
	printf("%lld", ans);
	return 0;
}
//因为数字可能很大所以用long long,需要注意的是n<=20,不然会超范围

combination:

//我们会发现其实组合和排列的实现几乎一模一样,只要算出阶乘就可以直接套公式了。
#include<stdio.h>
long long factorial(long long n)//计算结成
{
    
    
	if (n == 0 || n == 1)
		return 1;
	else
		return n * factorial(n - 1);
}
long long combination(long long n, long long m)//计算组合
{
    
    
	return factorial(n) / (factorial(n - m)* factorial(m));
}
int main()
{
    
    
	long long n, m;
	scanf("%lld %lld", &n, &m);//输入n和m
	long long  ans = combination(n, m);
	printf("%lld", ans);
	return 0;
}
//同样n要<=20.

However, this way of writing obviously cannot perform modulo operations.
So our next issue is about how to get remainders from permutations and combinations, so don’t forget to follow the blogger~ If you think the blogger’s talk is good, please give him a like and save it~ We’ll see you in the next issue! ( Upgraded version of permutation and combination algorithm! Click here!!! )

Guess you like

Origin blog.csdn.net/Tokai___Teio/article/details/135240693