c 随机行中帕斯卡三角形中所有系数的平方和

c sum of the squares of all the coefficients in pascals triangle in random row

所以我一直在努力解决这个问题,但就是做不到。问题是,我在三角形中放置了一些行,(可以是任意随机 number/row)并且程序应该 return 该行中所有系数的平方和。

#include <stdio.h>

unsigned long sum_triangle(const int row);

int main(){
 printf("%lu\n", sum_triangle(7));

 // sum(7)....7 is number of row

return 0;
}

unsigned long sum_triangle(const int row){
unsigned long sum = 0;
int temp =0;
for (int line = 0; line <= row ; line++) {
    for (int number = 0; number <= line ; number++){
        if (line == row){
            temp = THIS NEEDS TO BE COMBINED SOMEHOW(line , number);
            sum += (temp * temp);
        }
    }
 }
return sum;
}

问题出在“温度”上。我需要以某种方式组合行和数字,仅此而已。任何帮助将不胜感激。

sum of squares of a row有一个公式:

sum of row m squares = binomial(2m, m)

因此,您所需要的只是实现一个不会在合理大小的整数上溢出的适当 binomial。巧合的是,维基百科文章已经在 C 中实现了。将它们组合在一起:

// from https://en.wikipedia.org/wiki/Binomial_coefficient
unsigned long binomial(unsigned long n, unsigned long k) {
    unsigned long c = 1, i;
    if (k > n-k)
        k = n-k;
    for (i = 1; i <= k; i++, n--)
        c = c / i * n + c % i * n / i;
    return c;
}

unsigned long sum_triangle(int m) {
    return binomial(2*m, m);
}