P9502 『MGOI』Simple Round I | A. 魔法数字 题解

· · 题解

一种 \mathcal O(1) 没有循环的做法,可以说明我会数学,但不多。

2^m<n

两边同时取对数,得:

m<\log_2n

显然,由于我们需要满足小于这个条件,而 m,n 为整数,因此我们可以推导出:

m\leq \log_2(n-1)

由于我们最大化 m,所以:

m=\lfloor\log_2(n-1)\rfloor

代码非常短。

#include<bits/stdc++.h>
#define LL long long
using namespace std;
LL x;
int main()
{
    cin>>x;
    cout<<(long long)(log2(x-1)/2)*2;
}