题解 |HJ100 #等差数列#
等差数列
https://www.nowcoder.com/practice/f792cb014ed0474fb8f53389e7d9c07f
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { // 等差数列 2,5,8,11,14。。。。(从 2 开始的 3 为公差的等差数列)输出求等差数列前n项和 数据范围: 1≤n≤1000 1≤n≤1000 Scanner scanner = new Scanner(System.in); int i = scanner.nextInt(); System.out.println(countSequence(i)); } public static int countSequence(int num) { if (num == 1) { return 2; } else { //前 n-1项和+第n项 int numN = 2 + 3 * (num - 1); return countSequence(num - 1) + numN; } } }