Any way faster than pow() to compute an integer power of 10 in C++?

后端 未结 12 863
逝去的感伤
逝去的感伤 2020-12-05 13:25

I know power of 2 can be implemented using << operator. What about power of 10? Like 10^5? Is there any way faster than pow(10,5) in C++? It is a pretty straight-forw

12条回答
  •  庸人自扰
    2020-12-05 14:03

    A solution for any base using template meta-programming :

    template
    struct pow {
        enum { value = E * pow::value };
    };
    
    template 
    struct pow {
        enum { value = 1 };
    };
    

    Then it can be used to generate a lookup-table that can be used at runtime :

    template
    long long quick_pow(unsigned int n) {
        static long long lookupTable[] = {
            pow::value, pow::value, pow::value,
            pow::value, pow::value, pow::value,
            pow::value, pow::value, pow::value,
            pow::value
        };
    
        return lookupTable[n];
    }
    

    This must be used with correct compiler flags in order to detect the possible overflows.

    Usage example :

    for(unsigned int n = 0; n < 10; ++n) {
        std::cout << quick_pow<10>(n) << std::endl;
    }
    

提交回复
热议问题