Good triangle
Source file: good.c | good.cpp | good.java, Input file: good.in, output file: good.out
Problem Description
The nth Triangular number, T(n) = 1 + ... + n, is the sum of the first n integers. It is the number of points in a triangular array with n points on side. For example T(4):
Write a program to compute the weighted sum of triangular numbers: W (n) = SUM[k = 1..n; k*T(k+1)].
X
X X
X X X
X X X X
Input Specifications
The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow.
Each dataset consists of a single line of input containing a single integer n, (1 ≤ n ≤300), which is the number of points on a side of the triangle.
Output Specifications
For each dataset, output on a single line the dataset number, (1 through N), a blank, the value of n for the dataset, a blank, and the weighted sum: W (n), of triangular numbers for n.
Sample Input/Output
good.in |
good.out |
4 3 4 5 10 |
1 3 45 2 4 105 3 5 210 4 10 2145
|
Solution :
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class Good { static int T(int n) { int i, s = 0; for (i = 1; i <= n; i++) s += i; return s; } static int w(int n) { int s = 0, k; for (k = 1; k <= n; k++) { s += k * T(k + 1); } return s; } public static void main(String[] args) throws NumberFormatException, IOException { int N, n, i, var = 0; BufferedReader in = new BufferedReader(new FileReader("good.in")); PrintWriter out = new PrintWriter(new FileWriter("good.out")); N = Integer.parseInt(in.readLine()); for (i = 1; i <= N; i++) { n = Integer.parseInt(in.readLine()); if (var != 0) out.println(""); var = 1; out.print(i + " " + n + " " + w(n)); } in.close(); out.close(); } }