如何在 C 中計算 2^100 的十位值?
我試過這個;
#include <cmath>
#include <iostream>
using namespace std;
int main(){
int answer;
answer=(unsigned long long int)pow(2, 100)%100/10;//zero
cout<<answer<<endl;
return 0;
}
但由于溢位,它列印了 0。
Python 使用此代碼正確列印答案;
print(2**100%100//10)
但是我如何在 C 中計算它呢?
uj5u.com熱心網友回復:
只需分兩步即可:
int x = (1<<25)%100;
x = (x*x*x*x)%100;
x = x/10;
uj5u.com熱心網友回復:
unsigned long long int不夠大,無法存盤 2**100。如果您使用的是 GCC 或 Clang,請嘗試__int128改用。
#include <cmath>
#include <cstdint>
#include <iostream>
int main(int argc, char **argv) {
int answer = ((__int128)std::pow(2, 100)) % 100 / 10;
std::cout << answer << '\n'; // 7
}
uj5u.com熱心網友回復:
你有型別轉換的問題。
從檔案中可以看到std::pow return double
所以第一步解決我們的問題,嘗試洗掉型別轉換。
std::pow(2, 100); // return 1.26765e 30
下一個我們不能使用operator%double 型別的問題,所以我們需要std::fmod
所以最終的解決方案看起來像這樣:
int answer= std::fmod(std::pow(2, 100), 100) / 10;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464865.html
