[백준 7523] Gauß (C#, C++) - soo:bak
작성일 :
문제 링크
설명
두 정수 a
, b
가 주어졌을 때, a
이상 b
이하 모든 정수의 합을 계산하는 문제입니다.
여러 개의 테스트케이스가 주어지며, 각 케이스는 "Scenario #i:"
형식의 타이틀과 함께 결과를 출력해야 합니다.
접근법
- 테스트케이스 수를 입력받습니다.
- 각 케이스마다 두 수
a
,b
를 입력받고, 등차수열의 합 공식을 활용하여 합을 구합니다.- 공식:
\(\text{합} = \frac{(a + b) \times (b - a + 1)}{2}\)
- 공식:
- 결과는
"Scenario #i:"
를 먼저 출력하고, 그 아래 줄에 합을 출력합니다. - 각 테스트케이스 사이에는 공백 줄을 한 줄씩 삽입합니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
class Program {
static void Main() {
int t = int.Parse(Console.ReadLine());
for (int i = 1; i <= t; i++) {
var parts = Console.ReadLine().Split();
long a = long.Parse(parts[0]);
long b = long.Parse(parts[1]);
long sum = (a + b) * (b - a + 1) / 2;
Console.WriteLine($"Scenario #{i}:");
Console.WriteLine(sum);
if (i < t) Console.WriteLine();
}
}
}
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 = 1; i <= t; i++) {
ll a, b; cin >> a >> b;
cout << "Scenario #" << i << ":" << (a + b) * (b - a + 1) / 2 << "\n";
if (i < t) cout << "\n";
}
return 0;
}