解决问题:
import java.math.BigInteger; public class YangHuiSanJiao { public static void main(String[] args){ System.out.println(solution(1000)); } /** * 求杨辉三角第n行第一个偶数出现的位置 * @param rowNum 第几行 * @return 第一个偶数出现的位置 * lizhen 2013/11/10 00:22 */ public static int solution(int rowNum){ int result = 0; if(rowNum == 1){ //第1行 return -1; } else if(rowNum % 2 != 0){ //除第1行外,第奇数行 return 2; } else { //第偶数行 result = location(rowNum); } return result; } /** * 求组合数,组合数计算方法:C(n,m)=n!/[m!(n-m)!] * @param start 相当于n * @param num 相当于m * @return 组合数 */ public static BigInteger total(int start,int num){ BigInteger result = factorial(start,num).divide(factorial(start-num,0)); return result; } /** * 求类似阶乘 * @param factor 因子 * @return 阶乘结果 */ public static BigInteger factorial(int factor,int end){ BigInteger result = new BigInteger("1"); for(int i=factor;i>end;i--){ result = result.multiply(new BigInteger(i+"")); } return result; } /** * 求杨辉三角第偶数行第一个偶数出现的位置 * @param rowNum 第偶数行 * @return 第一个偶数出现的位置 * lizhen 2013/11/10 00:22 */ public static int location(int evenNum){ int result = -1; int length = evenNum; int end = length/2; //由于杨辉三角对称,所以只判断第n行前一半数 for(int i=2;i<=end;i++){ BigInteger number = total(evenNum-1 , i-1); if(number.mod(new BigInteger(2+"")).equals(new BigInteger("0"))){ result = i; break; } } return result; } }
杨辉三角性质: