給定一位數字 a (1-9) 與項數 n,求 S = a + aa + aaa + ... (共 n 項) 的和。例如 a=2, n=5 時:2 + 22 + 222 + 2222 + 22222 = 24690。
import java.io.*;
public class SumLoopString {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("請輸入數字 a (1-9):");
String aStr = br.readLine();
System.out.print("請輸入項數 n:");
int n = Integer.parseInt(br.readLine());
long sum = 0;
String term = "";
for (int i = 0; i < n; i++) {
term += aStr; // "2" -> "22" -> "222" ...
sum += Long.parseLong(term);
}
System.out.println("總和 = " + sum);
}
}
利用字串連接產生每一項,再轉數值相加。直觀但因字串操作與解析,效能較差,適合教學示範。
import java.io.*;
public class SumLoopMath {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("請輸入數字 a (1-9):");
int a = Integer.parseInt(br.readLine());
System.out.print("請輸入項數 n:");
int n = Integer.parseInt(br.readLine());
long sum = 0, term = 0;
for (int i = 1; i <= n; i++) {
term = term * 10 + a; // 遞推:2 -> 22 -> 222 ...
sum += term;
System.out.println("第" + i + "項 = " + term);
}
System.out.println("總和 = " + sum);
}
}
觀察規律:term_i = term_{i-1} * 10 + a。純整數運算,時間 O(n),空間 O(1),無字串開銷,適合大量計算。
利用等比數列求和公式可進一步優化為 O(1):
S = a/9 * [ (10^1-1) + (10^2-1) + ... + (10^n-1) ] = a/9 * [ (10^(n+1)-10)/9 - n ]
實作時需注意整數除法順序與溢位,可使用 BigInteger 處理極大 n。