// CSC 240 - Diagnostic Q1 - Gauss Sum (CSC 141, loops) // Sum 81297 + 81495 + 81693 + ... + 100899 (each step adds the same amount). public class Q1_GaussSum { public static void main(String[] args) { int start = 81297; int end = 100899; int step = 198; // ANSWER 1: common step between terms // ANSWER 2: number of terms = (end - start) / step + 1 int terms = (end - start) / step + 1; System.out.println("Number of terms = " + terms); // 100 // ANSWER 3: the loop that accumulates the sum long sum = 0; // long is safest; here 9.1M fits an int too for (int v = start; v <= end; v += step) { sum += v; } System.out.println("Sum = " + sum); // 9109800 // Cross-check with Gauss's formula: terms * (first + last) / 2 long check = (long) terms * (start + end) / 2; System.out.println("Formula check = " + check); // 9109800 } }