打表找规律,发现 前n行 所有 偶数的个数公式 如下,
\quad (注意公式计算的结果 是 从0 层开始的 前n行的 偶数个数)
\quad (即 前4行 对应的 从0 层到 第 3层)
S 0 = S 1 = 0 S 2 n = 3 S n + n ( n − 1 ) 2 S 2 n + 1 = 2 S n + S n + 1 + n ( n + 1 ) 2 \quad S_0 = S_1=0 \\ \quad S_{2n}=3S_n+\frac{n(n-1)}{2} \\\quad S_{2n+1}= 2S_n+S_{n+1}+\frac{n(n+1)}{2} S0=S1=0S2n=3Sn+2n(n−1)S2n+1=2Sn+Sn+1+2n(n+1)
直接 递归+记忆化(解决多组数据时递归爆内存 使用map 记录) +大数
[杨辉三角的性质]https://blog.csdn.net/nefu__lian/article/details/108932343
前n 行 共有多少个数字 (即前n-1层),符合等差 数列公式,公差为1
S n = n a 1 + n ( n − 1 ) 2 d = n + n 2 − n 2 = n ( n + 1 ) 2 S_n= na_1+\frac{n(n-1)}{2}d= n+\frac{n^2-n}{2}= \frac{n(n+1)}{2} Sn=na1+2n(n−1)d=n+2n2−n=2n(n+1) (n 为行 即n-1层)
奇数个数=总数-偶数个数
注意这是前n行, 上面的代码时前 n 层
import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.math.BigInteger; public class Main{ static BigInteger one=BigInteger.ONE; static BigInteger zero=BigInteger.ZERO; static BigInteger two=BigInteger.valueOf(2); static BigInteger three=BigInteger.valueOf(3); static Map<BigInteger, BigInteger> mp=new HashMap<BigInteger, BigInteger>(); public static void main(String[] args) { Scanner in=new Scanner(System.in); BigInteger n,ans; while(in.hasNextBigInteger()) { n=in.nextBigInteger(); ans=f(n); System.out.println("前n行 偶数个数: "+ans); System.out.println("前n行 奇数个数: "+sum(n).subtract(ans)); } } static BigInteger f(BigInteger n) { // 前n行 偶数个数 BigInteger m,res; if(mp.get(n)!=null) return mp.get(n); if(n==one||n==zero) return zero; if(n.mod(two)==zero) { m=n.divide(two); res= three.multiply(f(m)) .add((m.multiply(m.subtract(one))).divide(two)); } else { m=n.subtract(one).divide(two); res=two.multiply(f(m)) .add(f(m.add(one))) .add(m.multiply(m.add(one)).divide(two)); } mp.put(n,res); return res; } static BigInteger sum(BigInteger n){ // 前n行 杨辉三角总数 return n.multiply(n.add(one)).divide(two); } }