HDU - 4349(卢卡斯定理)

HDU - 4349(卢卡斯定理)

Xiao Ming likes counting numbers very much, especially he is fond of counting odd numbers. Maybe he thinks it is the best way to show he is alone without a girl friend. The day 2011.11.11 comes. Seeing classmates walking with their girl friends, he coundn’t help running into his classroom, and then opened his maths book preparing to count odd numbers. He looked at his book, then he found a question “C (n,0)+C (n,1)+C (n,2)+…+C (n,n)=?”. Of course, Xiao Ming knew the answer, but he didn’t care about that , What he wanted to know was that how many odd numbers there were? Then he began to count odd numbers. When n is equal to 1, C (1,0)=C (1,1)=1, there are 2 odd numbers. When n is equal to 2, C (2,0)=C (2,2)=1, there are 2 odd numbers… Suddenly, he found a girl was watching him counting odd numbers. In order to show his gifts on maths, he wrote several big numbers what n would be equal to, but he found it was impossible to finished his tasks, then he sent a piece of information to you, and wanted you a excellent programmer to help him, he really didn’t want to let her down. Can you help him?
Input
Each line contains a integer n(1<=n<=10 8)
Output
A single line with the number of odd numbers of C (n,0),C (n,1),C (n,2)…C (n,n).
Sample Input
1
2
11
Sample Output
2
2
8

  • 题目大意:
    给你一个n,求C(n,1),C(n,2)……C(n,n)中奇数的个数
  • 解题思路:
    用卢卡斯定理解决就非常简单了。
    下面来简单介绍一下我所认知的卢卡斯定理

在这里插入图片描述

然后我们这个题 把 n 和m 都换成2进制数
a=akpk+ak−1pk−1+⋯+a1p+a0
b=bkpk+bk−1pk−1+⋯+b1p+b0
换成2 进制后,p=2,我们这这个定理中 C(0,1)=0;所以要c(n,m)为奇数,那就是 C(a1,b1) *……C(ak,bk)mod2=1; 也就是每一项都得是1 ,所以说 n%m==m的时候,C(n,m)就是奇数。
但是,我试过直接判断 n%m= =m,发现会超时 这样是 o(n)的复杂度 跑1e8恰好不行。所以我们换个角度来想 把n换成2进制后 n的0 只能对m的0 n的1 可以对m的1 和0 所以n的二进制中有cnt个1 就有2^cnt种组合方式,这复杂度就大大降低了。
具体代码如下:

#include <iostream>
#include <cstring>
using namespace std;


int main()
{
	int n;
	int m;
	while(cin>>n)
	{
		int cnt=0;
		while(n)
		{
			if(n%2==1)
				cnt++;
			n/=2;
		}
		int ans=1;
		for(int i=1;i<=cnt;i++)
		{
			ans*=2;
		}
		cout<<ans<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43179892/article/details/83722608