等差数列 2,5,8,11,14。。。。
(从 2 开始的 3 为公差的等差数列)
输出求等差数列前n项和
数据范围:
等差数列求和公式:Sn=a1*n+n*(n-1)*d/2 import java.util.*; public class Main{ public static void main(String[] args){ Scanner in = new Scanner(System.in); while(in.hasNext()){ int n = in.nextInt(); if(n<1){ System.out.println(-1); }else{ System.out.println((2*n+3*n*(n-1)/2)); } } in.close(); } }
利用等差数列求和公式:
import java.util.Scanner; /** * @author : cunyu * @version : 1.0 * @className : OneZeroZero * @date : 2020/8/8 18:58 * @description : 100.等差数列 */ public class OneZeroZero { public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = 0; while (in.hasNext()) { N = in.nextInt(); System.out.println(sumOfArray(N)); } } /** * @param N 前 N 项 * @return 前 N 项和 * @description 等差数列前 N 项和 * @date 2020/8/8 22:04 * @author cunyu1943 * @version 1.0 */ public static int sumOfArray(int N) { int start = 2; int distance = 3; // 等差数列求和公式 return N * start + N * (N - 1) * distance / 2; } }
import java.util.Scanner; import java.util.stream.Collectors; import java.util.stream.Stream; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextLong()) { int sum = Stream.iterate(2, n -> n + 3).limit(sc.nextLong()).collect(Collectors.summingInt(e -> e)); System.out.println(sum); } sc.close(); } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextInt()) { int n = sc.nextInt(); int count = -1; // 记录当前的值 int sum = 0; // 记录总和 for (int i = 0; i < n; i++) { count += 3; sum += count; } System.out.println(sum); } } }
n = int(input()) l =[] for i in range(n): m = 2 * i + 2 + i l.append(m) print(sum(l))
import java.util.*; /** * @author hll[yellowdradra@foxmail.com] * @description 等差数列 * @date 2021-05-13 22:33 **/ public class Main { public static void main(String[] args) { int d = 3; int a1 = 2; Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int n = scanner.nextInt(); int an = a1 + (n - 1) * d; int sn = (n * (a1 + an)) / 2; System.out.println(sn); } } }
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String strN; while((strN = br.readLine()) != null){ int n = Integer.parseInt(strN); // 等差数列求和公式 System.out.println((2 + 2 + (n - 1)*3)*n / 2); } } }