等差数列 2,5,8,11,14。。。。
(从 2 开始的 3 为公差的等差数列)
输出求等差数列前n项和
数据范围:
基本递归
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); System.out.print(sum(2, 3, n)); } public static int sum(int s, int d, int n) { if (n == 0) { return 0; } else { return sum(s+d, d, n-1) + s; } } }
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int m = sc.nextInt(); long total = 0L; while (m > 0) { total += 2 + (3 * (--m)); } System.out.println(total); } }
/** * 等差数列求和 (首项+末项)*项数/2 * 末项 a1+(n-)*d * 公式化简 na1+n*(n-1)*d/2 */ public static void equidistant100(){ Scanner sc=new Scanner(System.in); int n = sc.nextInt(); sc.close(); System.out.println(n*2+n*(n-1)*3/2); }
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 int a = in.nextInt(); int sum = 0; for (int j = 1; j <= a; j++) { sum += j*3 - 1; } System.out.println(sum); } }
import java.util.*; import java.math.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 Long n=in.nextLong(); //Sn=a1*n+n(n-1)d/2 Long d=3l; Long sum=2*n+(n*(n-1)*d)/2; System.out.print(sum); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * 等差数列 */ public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int result = 2; int sum = result; for (int i = 1; i < n; i++) { result += 3; sum = sum + result; } System.out.println(sum); } }
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); } } }