Java语言数列求值,计算1+1+2+4+6+7+12+...的前n项的值,没看懂这个规律,求助
完全看不懂规律,如果要强行解释,可以从7开始:
7=1+2+4
12=2+4+6
下一项:
4+6+7 = 17
瞎扯的,请无视
拆分数列,奇数项和偶数项
奇数项为: 1 4 7 11 .....
偶数项为: 1 2 6 12 即是 1 1*2 2*3 3*4 ....
public static int calculation(int digit) {
int singular = 1;
int flag = 0; // 当前循环次数
List<Integer> numList = new ArrayList<>();
numList.add(1);
numList.add(1);
int even = 1;
while (numList.size() < digit) {
flag++;
if (flag % 2 == 0) {
even += 3;
numList.add(even);
} else {
double num = singular * (singular + 1);
numList.add((int) num);
singular++;
}
}
final int[] count = {0};
final String[] str = {""};
numList.stream().forEach(num -> {
count[0] += num;
str[0] += num + " + ";
});
System.out.println(str[0].substring(0, str[0].length() - 2) + "= " + count[0]);
return count[0];
}