작성일 :

문제 링크

9713번 - Sum of Odd Sequence

설명

홀수 N이 주어질 때, 1부터 N까지의 모든 홀수의 합을 구하는 문제입니다.

예를 들어 N = 9이면 1 + 3 + 5 + 7 + 9 = 25를 출력합니다.


접근법

수학 공식을 사용하여 해결합니다.

1부터 N까지 홀수의 개수는 (N + 1) / 2입니다. 홀수가 k개 있을 때 첫 k개 홀수의 합은 입니다.


따라서 홀수의 개수를 구한 뒤 제곱하면 답을 바로 계산할 수 있습니다.



Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;

namespace Solution {
  class Program {
    static void Main(string[] args) {
      var t = int.Parse(Console.ReadLine()!);
      var outputs = new int[t];

      for (var i = 0; i < t; i++) {
        var n = int.Parse(Console.ReadLine()!);
        var count = (n + 1) / 2;
        outputs[i] = count * count;
      }

      Console.WriteLine(string.Join("\n", outputs));
    }
  }
}

C++

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

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

  int t; cin >> t;
  while (t--) {
    int n; cin >> n;
    int count = (n + 1) / 2;
    cout << count * count << "\n";
  }

  return 0;
}