c ++如何存储大小为2 ^ 1 000 000的变量和字符串?

时间:2018-02-16 14:23:45

标签: c++

我正在尝试解决一个练习。它表示我需要输出一个2的数字的最后数字,其中2是n(2 ^ n)的幂。

但输入为n=1000000

代码使用较低的值,但当输入为1 000 000时,数字太大。

我的代码:

#include <iostream>
#include <cmath>
#include <string> 

using namespace std;

int main()
{
    unsigned long long n;
    cin >> n;
    unsigned long long sk = pow(2, n);

    if (sk < 1000) cout << sk;

    else {
        string ats = to_string(sk);  // converting the number to string
                                     // so I could output 3 last digits
                                     // probably not the best solution
                                     // for this exercise
        n = ats.length();
        for (unsigned long long i = n - 3; i < n; i++) {
            cout << ats[i];
        }
    }
    return 0;
}

感谢您的帮助。

2 个答案:

答案 0 :(得分:5)

尝试类似:

  • 将结果初始化为1
  • 在从1到n的循环中:
    • 结果* = 2
    • 结果%= 1000

这是因为最后3位数的结果不依赖于更大的数字

答案 1 :(得分:0)

您可以计算模数为1000的数字。仅保存三个最低有效数字并删除更重要的数字不会改变结果。 只是做:

int result = 1;
for(int i = 0; i < n; i++){
    result = (result * 2) % 1000;
}