Description
Problems involving the computation of exact values of very large magnitude and precision are common. For example, the computation of the national debt is a taxing experience for many computer systems.
This problem requires that you write a program to compute the exact value of Rn where R is a real number ( 0.0 < R < 99.999) and n is an integer such that .
Input
The input will consist of a set of pairs of values for R and n. The R value will occupy columns 1 through 6, and the n value will be in columns 8 and 9.
Output
The output will consist of one line for each line of input giving the exact value of Rn. Leading zeros and insignificant trailing zeros should be suppressed in the output.
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
问题描述:
这题主要是一道高精度的的大数幂运算问题
题目要求:
输入两个数浮点数R,和整数n,求R^n
其中0.0 < R < 99.999
题目解析:
这题题目的时间要求比较长3000MS,所以可以用大数相乘,再循环n次,得出的大数没有小数点。
所以需要先记录下R小数点的位置,小数点之后的长度*n,就是小数点的位置。
#include<string> #include<iostream> #include<stdio.h> #include<string.h> using namespace std; const int MAX = 1000; void getNum(int num[],string str) { int len = str.size(); for(int i=0;i<len;i++) { num[len-1-i]=str[i]-'0'; } } void multiSolve(int num1[],int num2[],int sum[]) { for(int i=0;i<MAX;i++) for(int j=0;j<MAX;j++) { sum[i+j] += num1[i]*num2[j]; } for(int i=0;i<MAX*2-1;i++) { sum[i+1] += sum[i]/10; sum[i] = sum[i]%10; } } string multi(string str1,string str2) { int num1[MAX],num2[MAX],sum[MAX*2]; memset(num1,0,sizeof(num1)); memset(num2,0,sizeof(num2)); memset(sum,0,sizeof(sum)); getNum(num1,str1); getNum(num2,str2); multiSolve(num1,num2,sum); int count = MAX*2 - 1; while(sum[count]==0) { count--; } string strSum; char dig; for(int i=count ;i >= 0; i--) { dig=sum[i]+'0'; strSum.push_back(dig); } return strSum; } string power(string str,int pow) { int after; int doe; int pos = str.find('.'); int lenx; int len_str = str.size(); if(pos != string::npos) { str.erase(pos,1); lenx=str.size(); after = lenx - 1; doe = len_str - pos -1; } else { doe=0; } string sum="1"; for(int i=0; i<pow ; i++) { sum=multi(sum,str); } int len = sum.size(); string result; if(str[0] >= '1') { for(int i=0 ; i<len ;i++) { result.push_back(sum[i]); if( i== len - pow*doe -1 && doe != 0 ) { result.push_back('.'); } } } else { result.push_back('.'); for(int i=0;i< pow*after-len;i++) { result.push_back('0'); } result += sum; } return result; } int main() { string str; string result; int pow; while(cin>>str>>pow) { getchar(); result = power(str,pow); int len = result.size(); for(int i=len-1;i >= 0;i--) { if(result[i] == '0') result.erase(i,1); else break; } cout<<result<<endl; } return 0; }