POJ1001算法解析

来源:互联网 发布:m4步枪 知乎 编辑:程序博客网 时间:2024/06/05 06:43

POJ1001
求高精度幂
Time Limit: 500MS Memory Limit: 10000K
Total Submissions: 170716 Accepted: 41349

Description
对数值很大、精度很高的数进行高精度计算是一类十分常见的问题。比如,对国债进行计算就是属于这类问题。

现在要你解决的问题是:对一个实数R( 0.0 < R < 99.999 ),要求写程序精确计算 R 的 n 次方(Rn),其中n 是整数并且 0 < n <= 25。

Input
T输入包括多组 R 和 n。 R 的值占第 1 到第 6 列,n 的值占第 8 和第 9 列。

Output
对于每组输入,要求输出一行,该行包含精确的 R 的 n 次方。输出需要去掉前导的 0 后不要的 0 。如果输出是整数,不要输出小数点。

Sample Input

95.123 12
0.4321 20
5.1234 15
6.7592 9
98.999 10
1.0100 12

Sample Output

548815620517731830194541.899025343415715973535967221869852721
.00000005148554641076956121994511276767154838481760200726351203835429763013462401
43992025569.928573701266488041146654993318703707511666295476720493953024
29448126.764121021618164430206909037173276672
90429072743629540498.107596019456651774561044010001
1.126825030131969720661201

AC代码(C语言)

#include <stdio.h>#include <string.h>int len; // total length of exponentiation resultint product[126] = {0}; // storing result, at most length 5*25 + 1 = 126void multiply(int a[], int n){    int i;    int carry = 0; // a carry number in multiplying    for (i = 0; i < len; i++)    {        int temp = a[i]*n + carry;        a[i] = temp % 10;        carry = temp / 10;          }    while (carry)    {        a[i++] = carry % 10;        carry /= 10;    }    len = i;}int main(int argc, char* argv[]){    int n;  // power n    char s[6]; // real number R, at most the length is 6    while (scanf("%s %d", s, &n) != EOF)    {        int position=0, i=0, num=0, j=0;        for (i=0; i<strlen(s); i++)         {            if (s[i] == '.')            {                position = (strlen(s) - 1 - i) * n; // calculate decimal point position after R^n            }            else            {                num = num*10 + s[i] - 48; // transfer float to integer            }               }        // product calculation         product[0]=1;        len = 1;        for (i = 0; i < n; i++)        {            multiply(product, num);        }        // format output        if (len <= position) // product is less than 1        {            printf("."); // print decimal point            for (i=0; i<position-len; i++)            {                printf("0"); // print zero between decimal point and decimal            }            j = 0;            //while (product[j] == 0) // trim trailing zeros            //{            //    j++;            //}            for (i=len-1; i>=j; i--)            {                printf("%d", product[i]);            }        }           else        {            j=0;            while (product[j]==0 && j<position) // trim trailing zeros            {                j++;            }            for (i=len-1; i>=j; i--)            {                if (i+1 == position) // cause index in C language starts from 0                {                    printf(".");                }                printf("%d", product[i]);            }        }        printf("\n");    }}
原创粉丝点击