求N!的二进制表示中最低位1的位置
解答:等于是求N!的质因数2的个数
有两种代码表示方式
第一种:
假设是8! 有1 2 3 4 5 6 7 8
第一次 则它有 2 4 6 8四个具有2的质因数
第二次 2 4 6 8变为 1 2 3 4 则只有 2 4具有2的质因数
第三次 2 4 变为 1 2 则只有2 具有2的质因数
公式 f(n) = (n/2) + (n/4) + (n/8) + (n/16) + ...
/// <summary>
/// 获得N!的质因数2的个数
/// </summary>
/// <param name="n">N!中N的值</param>
/// <returns></returns>
public static int GetNum(int n)
{
int num;
num = 0;
while(n>0)
{
n >>= 1;
num += n;
}
return num;
}
第二种方法 遍历每个数 每个数的2 的质因数之和就是总的质因数
public static int GetAntherNum(int n)
{
int num;
num = 0;
for (int i = n; i > 1; )
{
while (i % 2 == 0 && i / 2 != 0)
{
num++;
i /= 2;
}
i = --n;
}
return num;
}