Count the Even Integers
时间限制: 1 Sec 内存限制: 128 MB提交: 52 解决: 16
[ 提交][ 状态][ 讨论版][命题人: admin]
题目描述
Yang Hui’s Triangle is defined as follow.
In the first layer, there are two numbers A1,1 and A1,2 satisfying A1,1 = A1,2 = 1.
Then for each i > 1, the i-th layer contains i + 1 numbers satisfying Ai,1 = Ai,i+1 = 1 and Ai,j = Ai−1,j−1 + Ai−1,j for 1 < j ≤ i.
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
Now, given an integer N , you are asked to count the number of even integers in the first N layers.
In the first layer, there are two numbers A1,1 and A1,2 satisfying A1,1 = A1,2 = 1.
Then for each i > 1, the i-th layer contains i + 1 numbers satisfying Ai,1 = Ai,i+1 = 1 and Ai,j = Ai−1,j−1 + Ai−1,j for 1 < j ≤ i.
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
Now, given an integer N , you are asked to count the number of even integers in the first N layers.
输入
The input file contains multiple cases, please handle it to the end of file.
For each case, there is only one line containing an integer N (0 < N ≤ 1050).
For each case, there is only one line containing an integer N (0 < N ≤ 1050).
输出
For each case, output the number of the even integers in the first N layers of Yang Hui’s Triangle.
样例输入
4
8
12
样例输出
4
16
42
提示
来源
【思路】
杨辉三角前 n 项 个数为 n*(n+1)/2
1.每行奇数个数一定为2^k(k为自然数)
2.当行数恰为2^k(k为自然数)时,奇数个数为2^k,偶数个数为零
3.当行数恰为2^k(k为自然数)时,奇数个数和恰为3^(k-1)
一个数 可以分解成 若干个 2^k 之和
所以 对数进行分解。
例如:2333 = 2048+256+16+8+4+1
通过暴力程序,我们可以找出2333的所有奇数个数为190985
那么,我们找出如下数字
行数 所有奇数个数
2048 177147
256 6561
16 81
8 27
4 9
1 1
我们可以发现:
177147×1 + 6561×2 + 81×4 + 27×8 + 9×16 + 1×32 恰好等于 190985!
[code]
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
static BigInteger one=BigInteger.ONE;
static BigInteger zero=BigInteger.ZERO;
static BigInteger n;
static BigInteger [] a=new BigInteger[171];
static BigInteger [] b=new BigInteger[171];
public static void init_b() {
b[0] =one;
for(int i=1;i<=170;i++)
{
b[i]=b[i-1].multiply(BigInteger.valueOf(3));
}
}
public static void init_a(BigInteger n){
BigInteger x=one;
x=x.shiftLeft(170);
BigInteger t=new BigInteger("170");
a[0]=zero;
while (n!=zero)
{
if(n.compareTo(x)>0||n.equals(x))
{
n=n.subtract(x);
a[0]=a[0].add(one);
a[a[0].intValue()]=t;
}
x=x.divide(BigInteger.valueOf(2));
t=t.subtract(one);
}
}
public static void main(String[] args){
Scanner cin =new Scanner(System.in);
while(cin.hasNext())
{
n=cin.nextBigInteger();
n=n.add(one);
init_b();
init_a(n);
BigInteger ans;
ans = zero;
for(int i=1;i<=a[0].intValue();i++)
{
BigInteger tep=b[a[i].intValue()];
BigInteger x=one;
tep=tep.multiply(x.shiftLeft(i-1));
ans = ans.add(tep);
}
// System.out.println(ans);
BigInteger sum= n.multiply(n.add(one));
sum=sum.divide(BigInteger.valueOf(2));
//System.out.println(sum);
ans= sum.subtract(ans);
System.out.println(ans);
}
}
}
123