1

I'm pretty sure it's only a small mistake but I don't know why it is not working..?

I would really appreciate if you could help me out!

#include <stdio.h>

int fak(int n) {
    int fak_n;
    if (n <= 1) {
        fak_n = 1;
    }
    for (int i = 2; i <= n; i++) {
        fak_n = fak_n * i;
    }
    return fak_n;
}

int bin(int n, int k) {
    return fak(n) / (fak(k) * fak(n - k));
}
        
int main() {
    int n;
    int k;
    scanf("%d%d", &n, &k);
    printf("%d\n", bin(n, k));
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • 1
    You might consider "long int" or so instead of simple "int": you might fall into overflow related issues. – Dominique May 21 '21 at 11:25

2 Answers2

2

fak_n is used without initialization when n is larger than 1. The initialization should be done unconditionally like this:

int fak(int n) {
    int fak_n=1;
    for(int i=2; i<=n; i++){
        fak_n=fak_n*i;
    }
    return fak_n;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
1

There are 2 problems in your code:

  • fak_n is not initialized in the fak() function. You should write:

      int fak(int n) {
          int fak_n = 1;
          for (int i = 2; i <= n; i++) {
              fak_n = fak_n * i;
          }
          return fak_n;
      }
    
  • type int has a limited range, typically 31 bits, so it can only represent factorials up to fak(12), so computing bin(13,1) which is 13, will cause an arithmetic overflow and produce an incorrect value. You should use a larger type such as unsigned long long and use a different formula.

Here is a modified version:

#include <stdio.h>

unsigned long long fak(int n) {
    unsigned long long fak_n = 1;
    for (int i = 2; i <= n; i++) {
        fak_n = fak_n * i;
    }
    return fak_n;
}

unsigned long long bin(int n, int k) {
    // check definition domain
    if (k < 0 || k > n || n < 0)
        return 0;
    // use factorials for small values
    if (n <= 20)
        return fak(n) / fak(k) / fak(n - k);
    // use Pascal triangle for larger ones
    return bin(n - 1, k - 1) + bin(n - 1, k);
}
        
int main() {
    int n, k;
    if (scanf("%d%d", &n, &k) == 2) {
        printf("%lld\n", bin(n, k));
    }
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189