작성일 :

문제 링크

26550번 - Ornaments

설명

층마다 삼각형 모양으로 배치된 장식 개수를 합해 전체 장식 수를 출력하는 문제입니다.


접근법

층 i의 장식 개수는 삼각수 i(i+1)/2입니다. 1부터 n까지 합하면 전체 개수는 n(n+1)(n+2)/6이므로 이를 그대로 계산해 출력합니다.


Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
using System;

class Program {
  static void Main() {
    var t = int.Parse(Console.ReadLine()!);
    for (var i = 0; i < t; i++) {
      var n = long.Parse(Console.ReadLine()!);
      var total = n * (n + 1) * (n + 2) / 6;
      Console.WriteLine(total);
    }
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int t; cin >> t;
  for (int i = 0; i < t; i++) {
    ll n; cin >> n;
    ll total = n * (n + 1) * (n + 2) / 6;
    cout << total << "\n";
  }

  return 0;
}