백준

백준 9506번 c#

대왕군 2024. 1. 30. 18:03

 

using System;
using System.Collections.Generic;

namespace Baekjoon
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //그냥 콘솔창 예쁘게 꾸미는 코드(심심해서 넣음)
            Console.BackgroundColor = ConsoleColor.DarkCyan;

            //입력값 받아올 변수
            int input = 0;
            //약수 넣을 리스트 변수 생성
            List<int> list = new List<int>();

            //약수들을 합칠 변수
            int num = 0;
            //결과 문장 만들 변수
            string result = $"{input} =";

            //무한반복
            while (true)
            {
                //값 입력
                input = int.Parse(Console.ReadLine());

                //list, num, result 변수 초기화
                list.Clear();
                num = 0;
                result = $"{input} =";

                //만약 입력값이 -1이라면 반복문 종료
                if (input == -1)
                {
                    break;
                }

                //내 입력값에 맞춰 리스트에 약수를 넣음
                //이때 i가 1부터 시작하므로 자동으로 작은 약수부터 Add 됨
                //입력값은 약수로 넣을 필요가 없으므로 i < input으로 해줌
                for (int i = 1; i < input; i++)
                {
                    if (input % i == 0)
                    {
                        //리스트는 배열과 달리 가변적이라서 편함
                        list.Add(i);
                        //num변수에 약수들을 더함
                        num = num + i;
                    }
                }

                //만약 입력값과 약수의 합이 같다면 실행
                if (input == num)
                {
                    //result에 input과 list를 이용하여 결과문장 작성
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (i != list.Count - 1)
                        {
                            result += $" {list[i]} +";
                        }
                        else
                        {
                            result += $" {list[i]}";
                        }
                    }
                }
                //만약 입력값과 약수의 합이 다르다면 실행
                else
                {
                    //완전수가 아니라는 문장을 result에 대입
                    result = $"{input} is NOT perfect.";
                }
                //결과 출력
                Console.WriteLine(result);
            }
            

        }

    }
}