ZOJ 4081:Little Sub and Pascal's Triangle

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5860

Little Sub is about to take a math exam at school. As he is very confident, he believes there is no need for a review.

Little Sub's father, Mr.Potato, is nervous about Little Sub's attitude, so he gives Little Sub a task to do. To his surprise, Little Sub finishes the task quickly and perfectly and even solves the most difficult problem in the task.

Mr.Potato trys to find any possible mistake on the task paper and suddenly notices an interesting problem. It's a problem related to Pascal's Triangle.

“math”/

The definition of Pascal's Triangle is given below:

The first element and the last element of each row in Pascal's Triangle is , and the -th element of the -th row equals to the sum of the -th and the -th element of the -th row.

According to the definition, it's not hard to deduce the first few lines of the Pascal's Triangle, which is:





......

In the task, Little Sub is required to calculate the number of odd elements in the 126th row of Pascal's Triangle.

Mr.Potato now comes up with a harder version of this problem. He gives you many queries on this problem, but the row number may be extremely large. For each query, please help Little Sub calculate the number of odd elements in the -th row of Pascal's Triangle.

Input

There are multiple test cases. The first line of the input contains an integer (), indicating the number of test cases. For each test case:

The first and only line contains an integer (), indicating the required row number in Pascal's Triangle.

Output

For each test case, output the number of odd numbers in the -th line.

Sample Input

3
3
4
5

Sample Output

2
4
2

题意:求杨辉三角的第i行有多少奇数

编写一个程序输出杨辉三角每一行奇数的数目。

发现每2的次方一循环,前2^(i-1)个相同,后2^(i-1)为前面的2倍。

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define ll long long
ll f(ll a)
{
	ll i,s;
	if(a==1)
		return 1;
	if(a==2)
		return 2;
	s=1;		
	for(i=1;;i++)
	{
		s*=2;
		if(a == s)
			return a;
		if(a < s)
			break;
	}
	if(a > s/2 + s/4)
		return 2*f(a-s/2);
	else
		return f(a-s/4);
}
int main()
{
	ll k;
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%lld",&k);
		printf("%lld
",f(k));
	}
	return 0;
}

也可以数k-1的二进制有多少1,答案为2的1的个数次方。

#include<stdio.h>
#define ll long long
int main()
{
	ll k,ans;
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%lld",&k);
		k--;
		ans=1;
		while(k)
		{
			if(k%2)
				ans*=2;
			k/=2;
		}
		printf("%lld
",ans);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/zyq1758043090/p/11852811.html