快速幂计算 Power Calculus
题面翻译
读入 n n n ( 1 ≤ n ≤ 1000 ) (1\le n\le 1000) (1≤n≤1000),问最少几次乘除法可以从 x x x得到 x n x^n xn,例如 x 31 x^{31} x31需要6次: x 2 x^{2} x2 = = = x ⋅ x x\cdot x x⋅x, x 4 x^{4} x4 = = = x 2 ⋅ x^{2}\cdot x2⋅ x 2 , x^{2}, x2, … , \dots , …, x 32 x^{32} x32 = = = x 16 ⋅ x 16 , x^{16}\cdot x^{16}, x16⋅x16, x 31 x^{31} x31 = = = x 32 ÷ x x^{32}÷x x32÷x
题目描述
代码
#include<bits/stdc++.h>
using namespace std;
int n,k;
int a[101];
bool aa(int bu,int s)//DFS
{
if(s<=0||pow(2,k-bu)*s<n||bu>k)
{
return 0;
}
if(s==n||pow(2,k-bu)*s==n)
{
return 1;
}
a[bu]=s;
for(int i=0;i<=bu;i++)
{
if(aa(bu+1,s+a[i])||aa(bu+1,s-a[i]))
{
return 1;
}
else
{
continue;
}
}
return 0;
}
int main()
{
while(scanf("%d",&n)==1)
{
if(n==0)
{
break;
}
k=0;
a[0]=1;
if(n==1)
{
cout<<0<<endl;
continue;
}
while(aa(0,1)==0)
{
k++;
}
cout<<k<<endl;
}
return 0;
}