思路
暴力
直接模拟
方法:方如其名,直接模拟,期望得分——。
评测记录。
暴力代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
int T,k;
signed main()
{
cin>>T;
while(T--)
{
cin>>k;
if(k==0)
{
cout<<"NO!";
break;
}
double r=k+0.5;
int ans=0;
while((int)r!=r)
{
ans++;
r*=double((int)r+1);
}
cout<<ans<<endl;
}
return 0;
}超时分析
样例较大, 至 行的数据转化耗费了过多时间。
优化
每乘一次相当于将原数字减少一个因数——。
以上结论的证明
在输入转浮点数首次操作时,有两种情况,在此分类讨论。
情况 1:
,设 ,转化后为 ,可以证明以上为整数,程序结束。
情况 2:
,设 ,转化后为 ,可以得出以上式子除以 等于 (假设 是奇数),而原来的 是偶数,所以减少了一个因数 ,程序继续执行以上逻辑,依旧是两种情况,直到变成情况 ,结束程序。
代码(AC记录)
#include<bits/stdc++.h>
#define int long long
using namespace std;
int T,k;
signed main()
{
cin>>T;
while(T--)
{
cin>>k;
if(k==0)
{
cout<<"NO!";
continue;
}
int ans=1;
while(k%2==0)
{
ans++;
k/=2;
}
cout<<ans<<endl;
}
return 0;
}找规律
暴力不好过,打表找规律。
通过打表,可得:
如果 为 二进制中 的个数,那么次数就是 。 时应特判输出 NO。
AC代码
#include<bits/stdc++.h>
#define int long long
#define lowbit(x) (x)&(-(x))
using namespace std;
int T,k;
signed main()
{
cin>>T;
while(T--)
{
cin>>k;
if(k==0)
{
cout<<"NO!";
break;
}
cout<<log2(lowbit(k))+1<<endl;
}
return 0;
}代码合集
所以本题共有 种方法可以 AC 。
方法 2
#include<bits/stdc++.h>
#define int long long
using namespace std;
int T,k;
signed main()
{
cin>>T;
while(T--)
{
cin>>k;
if(k==0)
{
cout<<"NO!";
continue;
}
int ans=1;
while(k%2==0)
{
ans++;
k/=2;
}
cout<<ans<<endl;
}
return 0;
}方法 3
#include<bits/stdc++.h>
#define int long long
#define lowbit(x) (x)&(-(x))
using namespace std;
int T,k;
signed main()
{
cin>>T;
while(T--)
{
cin>>k;
if(k==0)
{
cout<<"NO!";
break;
}
cout<<log2(lowbit(k))+1<<endl;
}
return 0;
}