HJ100 等差数列
法一
通项公式:
an=a1+(n−1)d
前n项和:
Sn=n(a1+an)/2
import java.util.*;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int first = 2, last = n * 3 - 1;int sum = (first + last) * n / 2;System.out.println(sum);}
}
法二
import java.util.*;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int sum = 0;//判断是否长度为1if (n == 1) {System.out.println(2);} else if (n > 1) {for (int i = 2 ; i <= 2 + (n - 1) * 3 ; i += 3) {sum += i;}System.out.println(sum);}}
}
法三
import java.util.*;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int sum = 2 * n + n*(n-1)*3/2;System.out.println(sum);}
}
知识点:
等差数列,用数学运算进一步化简,可以写为
Sn=n(a1+an)/2
an=a1+(n−1)d
Sn = n(a1+(a1+(n-1)d)/2
也就是最终:
等差数列前N项公式和:
Sn=n * a1+[n * (n-1) * d]/2