當n=1時總共有1個大小為1的格子
當n=2時總共有4個大小為1的格子,1個大小為2的格子
當n=3時總共有9個大小為1的格子,4個大小為2的格子,1個大小為3的格子
依此類推
n | ans | n=1的方形的數量(1~100的平方數) | n=2 | n=3 | n=4 |
1 | 1 | 1 | |||
2 | 5 (1 + 4) | 4 | 1 | ||
3 | 14 (1 + 4 + 9) | 9 | 4 | 1 | |
4 | 30 (1 + 4 + 9 + 16) | 16 | 9 | 4 | 1 |
先將1~100的平方數放入陣列
再將平方數累加放進answer array裡面。
n = 1
n = 2
n = 3
import java.util.*;
public class main{
public static void main(String[] args) {
try{
final int max = 100;
int[] square = new int[101];
int[] ans = new int[101];
// 1 4 9 16 ......
for(int i = 1; i <= max; i++){
square[i] = i * i;
}
// 1 5 14 30 ...... , (1 1+4 1+4+9 1+4+9+16 ......)
int sum = 0;
for(int i = 1; i <= max; i++){
sum += square[i];
ans[i] = sum;
}
Scanner in=new Scanner(System.in);
int a;
while(in.hasNextInt() == true){
a = in.nextInt();
if(0 == a){
break;
}
System.out.println("" + ans[a]);
}
in.close();
}catch(Exception e){
System.out.println("Input error!");
}
}
};
留言列表