Number of XTU-OJ combinations

Question description

2n=C(n,0)+C(n,1)+…+C(n,n). Among them, represents power, and C(n,x) represents the number of combinations, that is, C(n,x)=n!/((n-x)!x!). Now I give you n (0<=n<=33), and I want you to output the expression of the sum of the combinatorial numbers of 2^n written in c language

enter

Each line contains an integer n. If n is a negative number, the input ends.

output

Each line outputs an expression, and the expression format is 2^n=C(n,0)+C(n,1)+…+C(n,n).

Sample input

2
3
-1

Sample output

2^2=1+2+1
2^3=1+3+3+1

Problem-solving ideas

This question can be understood and calculated more intuitively using Yang Hui's triangle.

Yang Hui's triangle is a numerical triangle in which each number is the sum of the two numbers above it:

              1
           1     1
        1     2     1
     1     3     3     1
  1     4     6     4     1

Because each number is the sum of the two numbers above it, and C(n, x) represents the number of combinations of x elements selected from n elements, each number in Yang Hui's triangle can be regarded as a corresponding The number of combinations C(n, x). In other words, the number in row n and column x of Yang Hui's triangle is C(n, x).

Therefore, we can first calculate the n+1th row of Yang Hui's triangle corresponding to 2^n (because the number of rows starts counting from 0, the number of rows corresponding to the range n required by the question is n+1), and then add the Adding all the numbers in the row gives us the sum of 2^n combinations.

Sample code

#include<stdio.h>

void pd(int n) {
    
    
    printf("2^%d=", n);

    float result;
    for (int i = 0; i <= n; i++) {
    
    
        result = 1;
        for (int j = 0; j < i; j++) {
    
    
            if (i == j){
    
    
                result = 1;
            }
            else {
    
    
                result = result * (n - j) / (i - j);
            }
        }
        printf("%.f", result);
        if (i != n){
    
    
            printf("+");
        }
        else {
    
    
            printf("\n");
        }
    }
}

int main(){
    
    
    int n;
    while (scanf("%d", &n)) {
    
    
        if (n < 0)
            break;
        pd(n);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_53961667/article/details/134344874