计算M的N次幂

作者: Albert_Sun | 来源:发表于2016-09-13 21:29 被阅读99次

    当指数非常大时候(比如1000,10000),直接调用C的库函数,会导致溢出。用此函数可正确计算指数结果,无论指数的数量级有多大(需正确给定相应进制的位数即ARRAY_LEN)。

    /****
        *计算 M 的 N 次幂 M^^N,以C进制呈现结果;(C < 256)
        */
    #include <stdio.h>
    
    #define M 2
    #define N 9
    #defien C 10
    #define ARRAY_LEN (N / 3 + 1) //正确的长度是(logC(M))* N
    
    int main()
    {
        int array[ARRAY_LEN] = {0};
        int j = 0;
        array[ARRAY_LEN-1] = 1;
    
        for(j = 0; j < N; j++){
            int t = 0;
            for(int i = ARRAY_LEN-1; i > ARRAY_LEN - 1 - (j / 3 + 1) ; i--){
                int tmp = array[i] * M + t;
                array[i] = tmp % C;
                t = tmp/10;
            }
        }
    
        for( j = 0; j < ARRAY_LEN; j++){
              if( array[j] != 0)
                break;
        }
    
        for( ; j < ARRAY_LEN; j++){
            printf("%d",array[j]);
        }
    
        printf("\n");
    
        return 0;
    }
    

    完整实例图如下:
    2的9次幂:


    2^^9.png

    2的16次幂:


    2^^16.png
    2的10000次幂:
    2^^10000
    由于2的10000次幂结果太大,一般难以验证,为验证程序结果是否正确,调用了python自带的(python的math库和C的math库中的pow函数都会溢出)指数函数pow(2, 10000);两者结果截图如下,可验证其正确性:
    2^^10000.png

    相关文章

      网友评论

        本文标题:计算M的N次幂

        本文链接:https://www.haomeiwen.com/subject/oqtvettx.html