문제
n이 주어졌을 때, 1부터 n까지 합을 구하는 프로그램을 작성하시오.
입력
첫째 줄에 n (1 ≤ n ≤ 10,000)이 주어진다.
출력
1부터 n까지 합을 출력한다.
정직한 반복문
using System;
namespace Baekjoon
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
int input = int.Parse(Console.ReadLine());
for (int i = 1; i < input + 1; i++)
{
sum += i;
}
Console.WriteLine(sum);
}
}
}
1부터 N까지 합 구하는 공식
using System;
namespace Baekjoon
{
class Program
{
static void Main(string[] args)
{
// 1부터 n까지의 합 공식 n * (n+1) / 2
int n = int.Parse(Console.ReadLine());
Console.WriteLine(n * (n + 1) / 2);
}
}
}
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 2292 벌집 C# (0) | 2022.10.25 |
---|---|
[백준] 24060 알고리즘 수업 - 병합 정렬 1 (0) | 2022.10.16 |
[백준 3단계] C# 15552 빠른 A+B (StringBuilder, StringReader) (1) | 2022.09.20 |
[백준 1단계] C# 2884 알람시계 (1) | 2022.09.19 |
[백준 1단계] C# 2588 곱셈 (0) | 2022.09.05 |
댓글