본문 바로가기
알고리즘/백준

[백준 3단계 반복문] C# 8393 합

by 개발하는 디토 2022. 9. 20.

문제

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);
        }
    }
}

댓글