【高精度乘法】POJ2109
题目:http://poj.org/problem?id=2109
思路
我们直接看p的范围是
1
∼
1
0
101
1\sim 10^{101}
1∼10101,显然我们无法使用整型来完成,一种简单的思路是使用double
来存,因为它的范围大概是
1
0
−
300
∼
1
0
300
10^{-300}\sim10^{300}
10−300∼10300,然后再使用现成的pow(double,double)
来完成解答。不过这种方法过于投机取巧,我这里介绍一种基于二分查找和高精度乘法的思路
高精度乘法
我们需要使用数组来完成两个整数的相乘,关于这题,我们需要计算的是 a b a^b ab,即已知 a a a和 b b b求出结果
下面给出伪码
input:Integer a,b
output: vector A
POW(a,b)
将a转换为数组A表示,其中A[0]表示个位,A[length-1]表示最高位
repeat :(b-1)
//下面进行a*a计算
for i=0 to length-1
A[i]=A[i]*a
for i=0 to length-2
exceeded=A[i]/10
A[i]=A[i]%10
A[i+1]=A[i+1]+exceeded
while A[length-1]>=10
exceeded=A[length-1]/10
A[length-1]=A[length-1]%10
A.push_back(exceeded)
return A
二分查找
二分查找无需多说,由于k的范围是 1 ∼ 1 0 9 1\sim 10^9 1∼109,则我们按照这个区间进行二分查找就好了。
BINARY_SEARCH
low=1
high=1e9
while low <=high
mid=(low+high)/2
if POW(mid,n) < p
low=mid+1
else if POW(mid,n)>p
high=mid-1
else
find the result :mid
return mid
error("cant find the result")
代码
#include<iostream>
#include<string>
#include<vector>
using namespace std;
typedef long long ll;
string pow(ll k,int n)
{
vector<ll> num;
int temp=k;
while(temp!=0)
{
num.push_back(temp%10);
temp/=10;
}
for(int i=0;i<n-1;i++)
{
for(int j=0;j<num.size();j++)
{
num[j]*=k;
}
for(int j=0;j<num.size()-1;j++)
{
ll exceeded=num[j]/10;
num[j]%=10;
num[j+1]+=exceeded;
}
while(num[num.size()-1]>=10)
{
ll exceeded=num[num.size()-1]/10;
num[num.size()-1]%=10;
num.push_back(exceeded);
}
}
string ret;
for(int i=num.size()-1;i>=0;i--)
ret.push_back(num[i]+'0');
return ret;
}
bool mygreater(string &a,string &b)
{
if(a.size()>b.size())
{
return true;
}
else if(a.size()==b.size())
{
return a>=b;
}
else
return false;
}
int main()
{
string p;
int n;
while(cin>>n>>p)
{
ll low=1;
ll high=1e9;
bool flag=false;
while(low<=high)
{
ll mid=(low+high)>>1;
string temp=pow(mid,n);
if(temp==p)
{
flag=true;
cout<<mid<<endl;
break;
}
else
{
if(mygreater(temp,p))
{
high=mid-1;
}
else
{
low=mid+1;
}
}
}
if(flag==false)cout<<high<<endl;
}
return 0;
}