所以,如果你还没看过的话,我试着在http://projecteuler.net上做项目Euler的问题# 16。具体如下:
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?我在想如何在C++中表示数字2^1000时遇到了麻烦。我猜这其中一定有个诀窍,但我真的被卡住了。我并不是真的想要这个问题的答案,我只是想知道如何将这个数字表示为一个变量,或者如果有一个技巧,也许有人可以让我知道?
发布于 2013-01-19 08:16:13
将其表示为字符串。这意味着您需要编写两段代码:
有了这两个部分,就很容易了。
发布于 2013-01-19 08:30:45
对于这个问题,有一个值得了解的好算法:
2^1 = 2
2^2 = 2 x 2 = 2 + 2
2^3 = 2 x (2 x 2) = (2 + 2) + (2 + 2)
2^4 = 2 x [2 x ( 2 x 2)] = [(2 + 2) + (2 + 2)] + [(2 + 2) + (2 + 2)]因此,我们有一个根据addition运算计算2的幂的recursive定义:just add together two of the previous power of two.
这个link很好地处理了这个问题。
发布于 2013-01-19 10:56:11
这是一个完整的程序。这些数字保存在一个向量中。
#include <iostream>
#include <numeric>
#include <ostream>
#include <vector>
int main()
{
std::vector<unsigned int> digits;
digits.push_back(1); // 2 ** 0 = 1
const int limit = 1000;
for (int i = 0; i != limit; ++i)
{
// Invariant: digits holds the individual digits of the number 2 ** i
unsigned int carry = 0;
for (auto iter = digits.begin(); iter != digits.end(); ++iter)
{
unsigned int d = *iter;
d = 2 * d + carry;
carry = d / 10;
d = d % 10;
*iter = d;
}
if (carry != 0)
{
digits.push_back(carry);
}
}
unsigned int sum = std::accumulate(digits.cbegin(), digits.cend(), 0U);
std::cout << sum << std::endl;
return 0;
}https://stackoverflow.com/questions/14409721
复制相似问题