Problem
Chloe, the same as Vladik, is a competitive programmer. She didn’t have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let’s consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we’ve got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven’t used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n - 1).
Output
Print single integer — the integer at the k-th position in the obtained sequence.
Example
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
思路:从每个数字出现的位置找规律
1出现在1,3,5,7,9,11,13,15……位置(从2^0开始,间隔2^1,即1+2n,即(1+2n)*2^0,即质因子有0个2)
2出现在2,6,10,14……位置(从2^1开始,间隔2^2,即2+4n,即(1+2n)*2^1,即质因子有1个2)
3出现在4,12……位置(从2^2开始,间隔2^3,即4+8n,即(1+2n)*2^2,即质因子有2个2)
4出现在8……位置(从2^3开始,间隔2^4,即8+16n,即(1+2n)*2^3,即质因子中有3个2)
AC代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int n;
long long k;
int main()
{
scanf("%d %lld", &n, &k);
int ans = 0; //质因子中2的个数
while(1){
if(k%2 == 0){
ans++;
k /= 2;
}
else break;
}
printf("%d\n", ans + 1);
return 0;
}
优化一下
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int main()
{
long long int n, k, m = 1, i;
scanf("%lld %lld", &n, &k);
for(i = 1; i <= n; i++){
m <<= 1;
if(k%m != 0){
printf("%lld\n", i); eak;
}
}
return 0;
}
高技巧性位运算:
数n的位置是奇数个2^(n-1),该位置的二进制第n-1位一定是1,大于n-1的位可能为1,小于n-1的位一定为0;而2^(n-1)的二进制只有第n-1位是1,通过位对比就能得出答案。
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int n;
long long k;
int main()
{
scanf("%d %lld", &n, &k);
for(int i = 0; i < 52; i++){
if(1ll<<i & k){
printf("%d\n", i + 1);
break;
}
}
return 0;
}