본문 바로가기
공부/C#

C# 공부(8) 71~80

by 라이티아 2024. 8. 26.

71. 소수인지를 알아내는 정적 메소드
using System;

namespace P71
{
    class Program
    {
        static void Main(string[] args)
        {
            int count = 0;
            for (int i = 2; i <= 100; i++)
            {
                if (IsPrime(i))
                {
                    Console.Write($"{i} ");
                    count++;
                }
            }
            Console.WriteLine();
            Console.WriteLine(count);
        }

        private static bool IsPrime(int n)
        {
            for (int i = 2; i < n; i++)
            {
                if (n % i == 0) return false;
            }
            return true;
        }
    }
}


결과

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
25

 

이전에 했던 코드의 연장선이다. 대신 static으로 만든 메소드를 사용해서 좀더 코드가 단순화 되었다.

 

72. 윤년인지를 알아내는 정적 메소드

using System;
namespace P72
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int year = 2001; year <= 2100; year++)
            {
                if(YearCheck(year))
                {
                    Console.Write(year + " ");
                }
            }
        }

        static bool YearCheck(int year)
        {
            return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
        }
    }
}

 

결과

2004 2008 2012 2016 2020 2024 2028 2032 2036 2040 2044 2048 2052 2056 2060 2064 2068 2072 2076 2080 2084 2088 2092 2096 

 

73. 생애 계산기

using System;

namespace P73
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("생일 입력 : ");
            string birth = Console.ReadLine();
            string[] bArr = birth.Split('/');

            int bYear = int.Parse(bArr[0]);
            int bMonth = int.Parse(bArr[1]);
            int bDay = int.Parse(bArr[2]);

            int tYear = DateTime.Today.Year;
            int tMonth = DateTime.Today.Month;
            int tDay = DateTime.Today.Day;

            int totalDays = 0;

            totalDays += DayOfYear(tYear, tMonth, tDay);
            int yearDays = IsLeapYear(bYear) ? 366 : 365;
            totalDays += yearDays - DayOfYear(bYear, bMonth, bDay);

            for (int year = bYear + 1; year < tYear; year++)
            {
                if (IsLeapYear(year))
                    totalDays += 366;
                else
                    totalDays += 365;
            }
            Console.WriteLine(totalDays + "일");
        }

        static int[] days = { 0, 31, 69, 120, 90, 151, 181, 212, 243, 273, 304, 334 };

        public static int DayOfYear(int year, int month, int day)
        {
            return days[month - 1] + day + (month > 2 && IsLeapYear(year) ? 1 : 0);
        }

        private static bool IsLeapYear(int year) {
            return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
        }
    }
}

 

결과

생일 입력 : 2000/1/1
9004일

 

사용자에게 생일을 입력받아 일로 치환해주는 코드이다.

 

74. 피라미드 메소드

using System;

namespace P74
{
    class Program
    {
        static void Main(string[] args)
        {
            Draw(5);
            Draw(3);
        }

        private static void Draw(int n)
        {
            for (int i = 1; i <= n; i++)
            {
                for (int j = i; j < n; j++)
                    Console.Write(" ");
                for (int k = 1; k <= 2 * i - 1; k++)
                    Console.Write("*");
                Console.WriteLine();
            }
        }
    }
}

 

결과

    *
   ***
  *****
 *******
*********
  *
 ***
*****

 

이전에 만든 피라미드를 정적 메소드로 변환한 코드이다.

 

75. 팩토리얼을 계산하는 메소드

using System;

namespace P75
{
    class Program
    {
        static void Main(string[] args)
        {
            int sum = 0;
            for (int i = 1; i <= 10; i++)
            {
                sum += Factorial(i);
                Console.WriteLine($"{i,2}! : {Factorial(i), 10:N0}");
            }
            Console.WriteLine($"{sum:N0}");
        }
        private static int Factorial(int n)
        {
            int fact = 1;
            for(int i = 1; i <= n; i++)
            {
                fact *= i;
            }
            return fact;
        }
    }
}

 

결과

 1! :          1
 2! :          2
 3! :          6
 4! :         24
 5! :        120
 6! :        720
 7! :      5,040
 8! :     40,320
 9! :    362,880
10! :  3,628,800
4,037,913

 

팩토리얼을 계산하는 메소드를 만들어 이전에 만든 코드를 단순화시킨 코드이다.

 

76. 두 숫자 사이의 모든 정수 값을 더하는 메소드

using System;
namespace P76
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"1 ~ 100 합 {Sum(0,100)}");
            Console.WriteLine($"101 ~ 200 합 {Sum(101, 200)}");
        }
        private static int Sum(int n1, int n2)
        {
            int sum = 0;
            for (int i = n1; i <= n2; i++)
            {
                sum += i;
            }
            return sum;
        }
    }
}

 

결과

1 ~ 100 합 5050
101 ~ 200 합 15050

 

간단한 메소드를 정적 으로 만들어 보는 코드이다.

 

77. n의 m승을 계산하는 메소드

using System;

namespace P77
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 20; i++)
            {
                Console.WriteLine($"2 ^ {i} = {Power(2, i)}");
            }
        }
        private static int Power(int a, int b)
        {
            int p = 1;
            for (int i = 1; i <= b; i++)
            {
                p *= a;
            }
            return p;
        }
    }
}

 

결과

2 ^ 0 = 1
2 ^ 1 = 2
2 ^ 2 = 4
2 ^ 3 = 8
2 ^ 4 = 16
2 ^ 5 = 32
2 ^ 6 = 64
2 ^ 7 = 128
2 ^ 8 = 256
2 ^ 9 = 512
2 ^ 10 = 1024
2 ^ 11 = 2048
2 ^ 12 = 4096
2 ^ 13 = 8192
2 ^ 14 = 16384
2 ^ 15 = 32768
2 ^ 16 = 65536
2 ^ 17 = 131072
2 ^ 18 = 262144
2 ^ 19 = 524288

 

팩토리얼을 계산하는 간단한 메소드 코드이다.

 

78. 원의 면적을 계산하는 메소드

using System;
namespace P78
{
    class Program
    {
        static void Main(string[] args)
        {
            for (double r = 1; r <= 10; r++)
            {
                Console.WriteLine($"Area of circle wity radius {r,2} = {Circle(r)}");
            }
        }
        private static double Circle(double r)
        {
            return Math.PI * r * r;
        }
    }
}

 

결과

Area of circle wity radius  1 = 3.141592653589793
Area of circle wity radius  2 = 12.566370614359172
Area of circle wity radius  3 = 28.274333882308138
Area of circle wity radius  4 = 50.26548245743669
Area of circle wity radius  5 = 78.53981633974483
Area of circle wity radius  6 = 113.09733552923255
Area of circle wity radius  7 = 153.93804002589985
Area of circle wity radius  8 = 201.06192982974676
Area of circle wity radius  9 = 254.46900494077323
Area of circle wity radius 10 = 314.1592653589793

 

간단 메소드

 

79. 재귀 메소드 Power(x, y)

using System;

namespace P79 // 제귀함수
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("power x, y");
            Console.Write("x 입력 : ");
            string input = Console.ReadLine();
            Console.Write("y 입력 : ");
            string input2 = Console.ReadLine();
            Console.WriteLine($"{Power(Convert.ToDouble(input) , Convert.ToDouble(input2)) }");
        }
        private static double Power(double x, double y)
        {
            if (y == 0) return 1;
            else return x * Power(x, y-1);
        }
    }
}

 

결과

power x, y
x 입력 : 5
y 입력 : 5
3125

 

재귀를 사용해서 매소드를 더욱 간소화 하는 방법이다. 다만, 최적화에서는 -이니 생각을 하면서 사용하는게 좋다

 

80. 재귀 메소드로 팩토리얼 계산

using System;
namespace P80
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"5! = {Fact(5)}");
        }
        private static double Fact(double n)
        {
            if (n == 0) return 1;
            else return n * Fact(n - 1);
        }
    }
}

 

결과

5! = 120

 

재귀 함수로 팩토리얼을 계산하는 코드다.

 

 

 

 

 

 

전체적으로 메소드의 구분이 큰 키워드인 것 같다

'공부 > C#' 카테고리의 다른 글

C# 공부(10) 91~92(Part2 End)  (0) 2024.08.26
C# 공부(9) 81~90  (0) 2024.08.26
C# 공부(7) 61~70  (0) 2024.08.26
C# 공부(6) 57~60  (0) 2024.08.25
C# 공부(5) 51~56 (Part 1 End)  (0) 2024.08.24