Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of k + 1 consecutive ones, and then k consecutive zeroes.
Some examples of beautiful numbers:
12 (110);
1102 (610);
11110002 (12010);
1111100002 (49610).
More formally, the number is beautiful iff there exists some positive integer k such that the number is equal to (2k - 1) * (2k - 1).
Luba has got an integer number n, and she wants to find its greatest beautiful divisor. Help her to find it!
Input
The only line of input contains one number n (1 ≤ n ≤ 105) — the number Luba has got.
Output
Output one number — the greatest beautiful divisor of Luba’s number. It is obvious that the answer always exists.
Example
Input
3
Output
1
Input
992
Output
496
#include<iostream>
#include<math.h>
using namespace std;
int main(){
int N,k;
while(cin>>N)
{ int ans;
for(int i=1;i<=N;i++)
{
for(int k=0;k<100;k++)
{
int temp=(pow(2,k)-1)*pow(2,k-1);
if(temp==i)
{
ans=i;
}
}
}
cout<<ans<<endl;
}
return 0;
}
通过运行结果可以看出确实能够求出给定数据范围内最大的美丽的数。
但是提交会WA,重新看题,要求的是求出给定数据范围内最大的满足整除的美丽的数。
在意识到这个问题后修改代码,再次提交,出现超时。我的解决方法时一步步尝试缩小k,i的取值范围。(虽然不高明,但能AC~~)
#include<iostream>
#include<math.h>
using namespace std;
int main(){
int N,k,j;
cin>>N;
int ans=1;
for(int i=1;i<=N/2;i++)
{
j=2*i;
for(k=0;k<10;k++)
{
int temp=(pow(2,k)-1)*pow(2,k-1);
if(temp==j&&N%j==0)
{
ans=j;
}
}
}
cout<<ans<<endl;
return 0;
}
另外在网上看到一个代码学习一下
#include <bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
int dec(string s)
{
int len=s.length(),ans=0;
for(int i=0; i<len; i++)
ans+=(s[i]-'0')*(int)pow(2,len-1-i);
//利用字符串表示二进制数
return ans;
}
int main()
{
int n,p=1;
string i="110";
scanf("%d",&n);
while(dec(i)<=n)
{
if(n%dec(i)==0)
p=dec(i);
i="1"+i+"0";
}
printf("%d\n",p);
return 0;
}