欧拉计划–C++编程突破8
Problem 15
Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
问题15
从一个2×2网格的左上角开始,只能向右和向下移动,右下角正好有6条路。
通过一个20×20的网格有多少这样的路线?
解题思路:简单的排列组合问题,题目中的情况可以理解为四步中选择两步往下走(或者往右走都可以)。也就是C2/4种情况 = 4*3 / 2 = 6种。根据所求应该为C20/40,直接计算就可以,这里给出两种解法,一种是直接计算得到结果,另一种是通过递归得到结果,每一次累加上一步即往上或者往左的情况,通过累加得到总共步数(不考虑C20/40)
First-one
#include<stdio.h>
int main() {
long long n = 40, m = 20, ans = 1;
while (m > 1) {
if(n > 20) ans *= (n--);
if(m && ans % m == 0) ans /= (m--);
}
printf("%lld\n",ans);
return 0;
}
Second-one
#include<stdio.h>
int main() {
long long a[45][45];
for(int i = 0; i < 45; i++){
a[i][0] = 1;
a[i][i] = 1;
}
for(int i = 2; i < 45; i++) {
for(int j = 1; j < i; j++) {
a[i][j] = a[i-1][j] + a[i-1][j-1];
}
}
printf("%lld",a[40][20]);
}
验证answer = 137846528820
Problem 16
215 = 32768 and the sum of its digits is 3+2+7+6+8 = 26.
What is the sum of the digits of the number 21000?
问题16
215=32768,其数字之和为3+2+7+6+8 = 26。
数21000的数位之和是多少?
解题思路:乍一看很吓人,2的1000次幂,但是每次乘二进行进位需要进行1000次,稍微复杂度有点高(应该每次乘2也行。。),但是为了减少时间开销,我们采取每次乘1024,来减少时间复杂度,这样只需要进行100次的进位判断,方法跟之前的题很像,使用整型数组来记录每位,每进行一次计算过后进行进位判断即可。
#include<stdio.h>
#define max_n 400
int num[max_n + 5] = {0};
int main() {
num[0] = num[1] = 1;
for(int i = 0; i < 100; i++){
for (int j = 1; j <= num[0]; j++) num[j] *= 1024;
for (int k = 1; k <= num[0]; k++) {
if (num[k] < 10) continue;
num[k + 1] += num[k] / 10;
num[k] %= 10;
num[0] += (k == num[0]);
}
}
int sum = 0;
for(int i = num[0]; i >= 1; i--){
sum += num[i];
}
printf("%d\n",sum);
return 0;
}
验证answer = 1366