大数的m次幂

时间:2014-04-13 02:05:31

标签: c++ biginteger pow

输入文件中将有两个数字在1≤n,m <1之间。 100。 我应该显示m到电源n。当我使用pow(x,y)函数时它不能计算ex ::: 12到23的大整数通常应该显示6624737266949237011120128,但我的代码显示负数。任何人都可以解决这个问题吗?

3 个答案:

答案 0 :(得分:0)

在调用pow:

之前,尝试将您的基地存储在long double
long double base = 12;
long double result = pow(base, 23);

不需要since C++11,你可以得到这样一个很好的近似值:

#include <iomanip>
#include <iostream>
#include <cmath>

int main ()
{
    std::cout << std::fixed << std::setprecision(0) << pow(99, 99) << std::endl;
}

输出:

369729637649726802192985226395427290145296428445515959701359650120802601667133273280053721002700400354392780458116125965728631706472588849812738072765460822138161108630185181415759762204338929270784

但它是近似,例如Python2代码print 99 ** 99输出:

369729637649726772657187905628805440595668764281741102430259972423552570455277523421410650010128232727940978889548326540119429996769494359451621570193644014418071060667659301384999779999159200499899

要在C ++中获得准确的结果,您应该查看一些BigInt libraries

答案 1 :(得分:0)

你能展示你的源代码吗? 使用double足以存储结果 以下是我的测试代码供您参考:

#include <iostream>
#include <cmath>

using namespace std;

int main (int argc, char *argv[])
{
    double result = pow (12, 23);
    cout.precision (26);
    cout << "Result: " << result << endl;
}

答案 2 :(得分:0)

如果不使用外部库,这不是很难。将数字的数字存储在矢量中并逐位数字(就像在纸上一样)。

Example:

power(12,23):

Store as start->1->2->end

step 1 result: start->1->4->4->end
step 2 result: start->1->7->2->8->end

and so on...