ComputerScience/C# 2015. 5. 14. 10:07

break

break는 가장 가까운 순환문을 빠져 나온다.

break를 이용하여 순환문을 빠져나와 보자.


//--------------------------------------------------------------------------------------//

1과 1000사이의 소수를 출력해보자.


소수 : 1과 자기자신으로만 나누어지는 수


프로그래밍 하기 쉽도록 바꿔보자 -> 1과 자신을 제외한 다른 수로는 나누어 떨어지지 않는수 


반복횟수를 줄이는 방법

1과 자지신을 제외한 다른 수로는 나누어 떨어지지 않는 수 -> 4이상의 수 중에서 2부터 자신의 절ㄴ반값까지 어떤 수로 나누어도 떨어지지 않는수



using System;
//for break
namespace Com.JungBo.Logic{
    public class PrimNumber{
        public static bool IsPrime1(int n){
            bool isP = true;
            for (int i = 2; i < n; i++){
                if (n % i == 0){
                    isP = false;
                    break;
                }
            }
            return isP;
        }//
        public static bool IsPrime2(int n){
            bool isP = true;
            for (int i = 2; i <= n / 2; i++){
                if (n % i == 0){
                    isP = false;
                    break;
                }
            }
            return isP;
        }//
       
        public static void PrintPrime(int n){
            int count = 0;
            for (int i = 2; i <= n; i++){
                //if (IsPrime1(i)){//솟수라면
                if (IsPrime2(i)){//IsPrime2(i)==true 동일
                    Console.Write("{0}\t", i);
                    count++; //count=count+1과 동일
                }
            }
            Console.WriteLine();
            Console.WriteLine("2부터 {0}까지 약수: {1}개",
                n,count);
        }
    }
}
using System;
using Com.JungBo.Logic;
namespace Com.JungBo.Basic
{
    public class Program
    {
        public static void Main(string[] args)
        {
            PrimNumber.PrintPrime(1000);
        }
    }
}

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

스태틱 메소드(static method)  (0) 2015.05.13
네임스페이스(namespace)  (0) 2015.05.11
Math 클래스  (0) 2015.05.09
등차수열  (0) 2015.05.09
중첩 for문  (0) 2015.05.09