我觉得加深学习数学效果的方式,就是自己实现一遍,我这里用C语言实现了一下递归求麦粒总数的问题以求抛砖引玉
#include <stdio.h>
#include <stdlib.h>
struct result {
long cur_grid_wheat;
long sum_of_wheat;
};
struct result wheat(int grid)
{
struct result rst;
if (grid == 1) {
rst.cur_grid_wheat = 1;
rst.sum_of_wheat = 1;
} else {
struct result last_rst;
last_rst = wheat(grid - 1);
rst.cur_grid_wheat = last_rst.cur_grid_wheat * 2;
rst.sum_of_wheat = last_rst.sum_of_wheat + rst.cur_grid_wheat;
}
return rst;
}
int main(int argc, char *argv[])
{
struct result rst;
int grid_index = 0;
if (argc != 2) {
printf("Usage: %s grid_index\n", argv[0]);
return -1;
}
grid_index = atoi(argv[1]);
rst = wheat(grid_index);
printf("grid_index: %d\ncur_grid_wheat: %ld\nsum_of_wheat: %ld\n",
grid_index, rst.cur_grid_wheat, rst.sum_of_wheat);
return 0;
}
展开