hdu-4349(组合数的奇数个数-杨辉三角&Lucas定理)

Xiao Ming's Hope

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2560    Accepted Submission(s): 1751


Problem Description
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,0) ,C  (n,1) ,C  (n,2) ...C  (n,n),奇数的个数。 也就是C(n,i)%2==1的i的个数,其中(0<=i<=n).

解析:Lucas的应用,Lucas定理,见Lucas

根据Lucas有Lucas(n,m,p)=c(n%p,m%p)*Lucas(n/p,m/p,p) 

我们可以写成二进制的形式观察,比如 n=1001101,m是从000000到1001101的枚举,我们知道在该定理中


C(0,1)=0,因此如果n=1001101的0对应位置的m二进制位为1那么C(n,m) % 2==0,因此m对应n为0的


位置只能填0,而1的位置填0,填1都是1(C(1,0)=C(1,1)=1),不影响结果为奇数,并且保证不会


* 出n的范围,因此所有的情况即是n中1位置对应m位置0,1的枚举,那么结果很明显就是:2^(n中1的个数)

这里也可以画个图,

1

1  1

1 2  1

1  3  3   1

1   4  6   4  1

........

就是杨辉三角。把奇数看成1,偶数0

就是求第n+1行的奇数的个数。

#include <cmath>
using namespace std ;
 
int main()
{
    int n , ans ;
    while(scanf("%d",&n)!=EOF && n >= 1)
    {
        ans = 0 ;
        while(n)
        {
            if(n&1)ans++ ;
            n>>=1 ;
        }
        printf("%d\n",1<<ans);
    }
    return 0;
}

这里n只有10的8次,要是10的18次就要unsigned  long long防止溢出。

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

int main()
{
    unsigned long long n,ans;
    while (~scanf("%lld", &n))
    {
        ans = 0;
        while (n)
        {
            if(n & 1)
                ans++;
            n >>= 1;
        }
        long long a=1;
        for(int i=1; i<=ans; i++)a*=2;
        printf("%lld\n", a);
    }
    return 0;
}

//100000000000000000


猜你喜欢

转载自blog.csdn.net/yu121380/article/details/81041947