主题:[转帖]关于M的N次幂的高精度计算
g1021117
[专家分:40] 发布于 2007-12-31 15:07:00
谁知道的,请写下来,拜托了~!!!!!!!!!!!!!!!!!!!!!!1[em5][em4][em5][em5][em5][em4][em4][em4][em5][em5][em4][em4][em5][em5]
回复列表 (共3个回复)
沙发
雨中飞燕 [专家分:18980] 发布于 2008-01-07 16:33:00
using array
but no source code for you. because it's easy
板凳
bc594926180 [专家分:0] 发布于 2008-01-26 19:46:00
program ex1;
var m,n,i,j,s,k:integer;
a:array[1..1001] of longint;
begin
readln(m,n);
for i:=1 to 1000 do a[i]:=0;
a[1]:=1;
for i:=1 to n do
begin
for j:=1 to 1000 do a[j]:=a[j]*m;
for j:=1 to 1000 do
begin
a[j+1]:=a[j] div 10 +a[j+1];
a[j]:=a[j] mod 10;
end;
end;
k:=1000;
while a[k]=0 do
k:=k-1;
for i:=k downto 1 do write(a[i]);
end.
3 楼
游侠UFO [专家分:1200] 发布于 2008-02-04 00:41:00
关键是写出高精度乘法..然后用下面递推式的思路写吧..
a^(2n)=a^n*a^n
a^(2n+1)=a^n*a^n*a
这样的话a^100只需要乘6次,大大提高效率
我今天刚好写了个C++的代码..就发个C++的吧:
#include <iostream>
#include <string>
using namespace std;
string Mul(const string &Num1, const string &Num2)
{
string Ans;
int *a,*b,*c,Max,Len1,Len2,Len,k,x,y,z,i,j,w;
Len1=(int)Num1.length();
Len2=(int)Num2.length();
Len=Len1+Len2;
Max=Len;
a=new int[Len1];
for (i=0;i<=Len1-1;i++) a[i]=0;
b=new int[Len2];
for (i=0;i<=Len2-1;i++) b[i]=0;
c=new int[Len];
for (i=0;i<=Len-1;i++) c[i]=0;
k=0;
for (i=Len1-1;i>=0;i--) a[k++]=Num1[i]-'0';
k=0;
for (i=Len2-1;i>=0;i--) b[k++]=Num2[i]-'0';
for (i=0;i<=Len1-1;i++)
for (j=0;j<=Len2-1;j++)
{
x=a[i]*b[j];
y=x/10;
z=x%10;
w=i+j;
c[w]=c[w]+z;
c[w+1]=c[w+1]+c[w]/10+y;
c[w]=c[w]%10;
}
while (c[Len]==0 && Len>0 || Len>=Max) Len--;
for (i=Len;i>=0;i--) Ans.append(1,c[i]+'0');
return Ans;
}
string Pow(const string &Number, int n)
{
string Temp;
if (n%2==0)
{
Temp=Pow(Number, n/2);
return Mul(Temp, Temp);
}
else if (n>1)
{
Temp=Pow(Number, n/2);
Temp=Mul(Temp, Temp);
return Mul(Temp, Number);
}
else return Number;
}
int main()
{
string Number;
int n;
while (cin>>Number>>n)
{
size_t Dot=Number.find('.', 0);
string Ans;
if (Dot!=-1)
{
while (!Number.empty() && Number[Number.size()-1]=='0') Number.erase(Number.size()-1, 1);
if (Number[Number.size()-1]=='.')
{
Number.erase(Number.size()-1,1);
Dot=-1;
}
else
{
Dot=Number.size()-Dot-1;
if (Number.find('.',0)!=-1) Number.erase(Number.find('.',0), 1);
}
}
while (!Number.empty() && Number[0]=='0') Number.erase(0, 1);
if (n==0) cout<<1<<endl;
else if (Number.empty()) cout<<0<<endl;
else
{
Ans=Pow(Number, n);
if (Dot!=-1)
{
Dot=Dot*n;
if (Dot>Ans.size()) Ans.insert(0, Dot-Ans.size(), '0');
Ans.insert(Ans.size()-Dot, ".");
while (!Ans.empty() && Ans[Ans.size()-1]=='0') Ans.erase(Ans.size()-1, 1);
}
while (!Ans.empty() && Ans[0]=='0') Ans.erase(0, 1);
cout<<Ans<<endl;
}
}
return 0;
}
我来回复