下面代码仅供本人复习所用,实用性N低,各位飘过吧~~哈哈:>
// // 杨辉三角. // // 杨辉三角除每行第一个元素和最后一个原始均为 1 外, // 其他元素等于它上面左右两边的元素之和. // #include <cstdlib> #include <iostream> #include <iomanip> #include <stdexcept> #include <ctime> const size_t ROWS = 10; // // 二维数组法. // void pascalTriangle_array(unsigned long (*array)[ROWS], const size_t rows) { for (size_t i = 0; i < rows; ++i) { array[i][0] = array[i][i] = 1; } for (size_t i = 2; i < rows; ++i) { for (size_t j = 1; j < i; ++j) { array[i][j] = array[i - 1][j - 1] + array[i - 1][j]; } } } // // 一维列表法. // void pascalTriangle_list(unsigned long *list, const size_t rows) { unsigned long *pCurrRow, *pPrevRow; for (size_t i = 0; i < rows; ++i) { pCurrRow = list + i * (i + 1) / 2; *pCurrRow = *(pCurrRow + i) = 1; } for (size_t i = 2; i < rows; ++i) { pPrevRow = list + (i - 1) * i / 2; pCurrRow = list + i * (i + 1) / 2; for (size_t j = 1; j < i; ++j) { *(pCurrRow + j) = *(pPrevRow + j - 1) + *(pPrevRow + j); } } } double factorial(int n) { double result = n; while (0 < --n) { result *= n; } return result > 0 ? result : 1; } // // 数学公式法. // // 单项公式: n! / ((n-1)! * n!) // unsigned long pascalTriangle_fomula(const unsigned int row, const unsigned int col) { if (row < col) { throw std::invalid_argument("pascalTriangle_fomula()"); } return factorial(row) / (factorial(row - col) * factorial(col)); } // // 测试. // int main(void) { // // 数组方法. // unsigned long triangle[ROWS][ROWS]; pascalTriangle_array(triangle, ROWS); for (size_t i = 0; i < ROWS; ++i) { for (size_t j = 0; j <= i; ++j) { std::cout << std::left << std::setw(4) << triangle[i][j]; } std::cout << std::endl; } // // 列表方法. // unsigned long list[(1 + ROWS) * ROWS / 2]; unsigned long * pRow; pascalTriangle_list(list, ROWS); for (size_t i = 0; i < ROWS; ++i) { pRow = list + i * (i + 1) / 2; for (size_t j = 0; j <= i; ++j) { std::cout << std::left << std::setw(4) << *(pRow + j); } std::cout << std::endl; } // // 公式方法. // for (size_t i = 0; i < ROWS; ++i) { for (size_t j = 0; j <= i; ++j) { std::cout << std::left << std::setw(4) << pascalTriangle_fomula(i, j); } std::cout << std::endl; } return EXIT_SUCCESS; }