Some math related code for calculatin binomial coef, nth-fibonacci and sin
This commit is contained in:
parent
65d8891c0e
commit
715f6af296
3 changed files with 136 additions and 0 deletions
38
bincoef.c
Normal file
38
bincoef.c
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
#include <stdio.h>
|
||||
|
||||
/**
|
||||
* @brief Computes the binomial coefficient "n choose k" (nCk).
|
||||
*
|
||||
* This function calculates the number of ways to choose k elements from a set
|
||||
* of n elements without repetition and without order. It uses an efficient
|
||||
* multiplicative approach to avoid large intermediate factorials.
|
||||
*
|
||||
* @param n The total number of elements.
|
||||
* @param k The number of elements to choose.
|
||||
* @return The computed binomial coefficient (n choose k), or 0 if k > n.
|
||||
*/
|
||||
unsigned long long binomial_coefficient(unsigned int n, unsigned int k);
|
||||
|
||||
unsigned long long binomial_coefficient(unsigned int n, unsigned int k) {
|
||||
if (k > n)
|
||||
return 0;
|
||||
if (k == 0 || k == n)
|
||||
return 1;
|
||||
|
||||
if (k > n - k)
|
||||
k = n - k;
|
||||
|
||||
unsigned long long result = 1;
|
||||
for (unsigned int i = 1; i <= k; ++i) {
|
||||
result *= n - (k - i);
|
||||
result /= i;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
int main() {
|
||||
unsigned int n = 10, k = 3;
|
||||
printf("C(%u, %u) = %llu\n", n, k, binomial_coefficient(n, k));
|
||||
return 0;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue