Blog Content

    티스토리 뷰

    07.C# - 알고리즘 : 수열 구하기

    반응형
    예제1 : 1 - 2 + 3 - 4 + 5 ... +99 - 100 = ? 구하기

    using System;


    public class 간단수열
    {
        public static void Main(string[] args)
        {
            int total = 0;
            for (int i = 1; i <= 100; i++)
            {
                if (i % 2 == 1)
                {
                    total += i;
                }

                if (i % 2 == 0)
                {
                    total -= i;
                }

            }
            Console.WriteLine("{0}", total);
        }   
    }

    예제2 : 1/2 - 2/3 + 3/4 ... -99/99 + 99/100 = ?

    using System;


    public class 수열문제
    {
        public static void Main()
        {
            //[1] Input
            double sum = 0.0;

            //[2] Process
            for (int i = 1; i <= 99; i++)
            {
                if (i % 2 != 0)
                {
                    sum +=  i  / (double)(i + 1);
                }
                else
                {
                    sum -=  i  / (double)(i + 1);
                }
            }

            //[3] Output
            Console.WriteLine("{0}", sum);
        }
    }


    예제3 : 1 + 2 + 4 + 7 + 11 + 16 + 22 + ...

    using System;

    public class 수열퀴즈
    {
        public static void Main(string[] args)
        {
            //[1] Input
            int index = 0;
            int data = 1;
            int sum = 0;

            //[2] Process
            for (int i = 0; i < 20; i++)
            {
                Console.Write("{0} + ", data);
                sum += data;//1누적
                data = data + (i + 1); //다음번에 index를 더함   
            }

            //[3] Output
            Console.WriteLine("\n");
            Console.WriteLine(sum);
        }   
    }



    반응형

    Comments