我正在尝试解决一个练习。它表示我需要输出一个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;
}
感谢您的帮助。
答案 0 :(得分:5)
尝试类似:
这是因为最后3位数的结果不依赖于更大的数字
答案 1 :(得分:0)
您可以计算模数为1000的数字。仅保存三个最低有效数字并删除更重要的数字不会改变结果。 只是做:
int result = 1;
for(int i = 0; i < n; i++){
result = (result * 2) % 1000;
}