您的位置:首页 > 其它

Project Euler Problem 16 Power digit sum

2017-03-22 19:27 393 查看
Power digit sum

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?

C++:

#include <iostream>
#include <cstring>

using namespace std;

const int MAXN = 1000;

int result[MAXN+1];

int power(int a, int n)
{
int digits, j;

memset(result, 0, sizeof(result));

result[0] = a;
digits = 1;
for(int i=2; i<=n; i++) {
int carry = 0;

for(j=0; j<digits; j++)
result[j] *= a;

for(j=0; j<=digits; j++) {
result[j] += carry;
carry = result[j] / 10;
result[j] %= 10;
}
digits = j;
}

return digits;
}

int main()
{
int n, digits;

while(cin >> n) {
digits = power(2, n);
int sum = 0;
for(int i=0; i<=digits; i++)
sum += result[i];
cout << sum << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: