简体   繁体   English

在 C/C++ 中快速得到 10 的 n(10^n) 次方

[英]FAST get 10 to the power n(10^n) in C/C++

well thanks for clicking in. i want to calculate 10(yes only 10) to the power n[0..308] fast.好吧,感谢您点击。我想快速计算 10(是的,只有 10)的 n[0..308] 次方。 i came up with some methods.我想出了一些方法。

1) 1)

double f(int n) {
  return pow(10.0, n);
}
double f1(int n) {
  double a = 10.0;
  double res = 1.0;
  while(n) {
    if(n&1) res *= a;
    a *= a;
    n >>= 1;
  }
  return res;
}

time: O(logn), could it be faster?时间:O(logn),可以更快吗? ( // f1() can do a little bit optimization but still O(logn)) ( // f1() 可以做一些优化,但仍然是 O(logn))

2) 2)

double f2(int n) {
  static const double e[] = { 1e+0, 1e+1, 1e+2, ..., 1e+308 };
  return e[n];
}

time: O(1), very good.时间:O(1),非常好。 But space: 309 * 8 bytes = 2472 bytes.. whoops it's too huge...但是空间:309 * 8 字节 = 2472 字节..哎呀它太大了......

3) 3)

double f3(int n){
    static const double e[] = {
        1e+1, 1e+2, 1e+4, 1e+8, 1e+16, 1e+32, 1e+64, 1e+128, 1e+256
    };
    double res = 1.0;
    for(int i = 0; n; ++i){
        if(n & 1){
            res *= e[i];
        }
        n >>= 1;
    }
    return res;
}

f3 combines f1 and f2 to avoid multiplication such as 1e128*1e128, i wished it faster, but.. actually f3 is slower than f2.. because of ++ii guess.. f3 结合了 f1 和 f2 以避免乘法,例如 1e128*1e128,我希望它更快,但是.. 实际上 f3 比 f2 慢.. 因为 ++ii 猜测..

well i almost gave up before i typed these codes,好吧,在我输入这些代码之前我几乎放弃了,

int main(){
    double d = 1e+2;
    return 0;
}

and compiled it to .s by g++并通过 g++ 将其编译为 .s

LCPI0_0:
    .quad   0x4059000000000000              ## double 100

HOW does the compiler know 1e+2 is 0x4059000000000000?编译器如何知道 1e+2 是 0x4059000000000000?

i mean all i want to get is a double values 1e+n.我的意思是我想要得到的只是一个双值 1e+n。 but when a compiler compiles "double d = 1e+2", it know d should be 0x4059000000000000.但是当编译器编译“double d = 1e+2”时,它知道 d 应该是 0x4059000000000000。 can i just use some method to directly return something like 1e+n.我可以使用某种方法直接返回像 1e+n. OR can i do some things beyond C/C++ to get my value?或者我可以做一些 C/C++ 以外的事情来获得我的价值吗?

thanks a lot.多谢。 Please point out if there is something wrong or unclear.如果有什么不对或不清楚的地方,请指出。

Have you tried std::pow(std::valarray) ?你试过std::pow(std::valarray)吗? 🤔 🤔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM