작은숲:위키노트/C 언어 예제/소수 찾기

큰숲백과, 나무를 보지 말고 큰 숲을 보라.
/**
 * Copyright (c) 2001,2002 Yoon, Hyunho <hhyoon@kldp.org>
 * http://mooo.org
 * ----------------------------------------------------------------------
 *
 * LICENSE
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software 
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
#include <stdio.h>
void main ()
{    int i, j;
    for(i = 2; i <= 100; i++) {
        /**
         * 1과 자기 자신을 제외한 수로 나누었을 때 나누어 떨어지는지 검사한다.
         * 즉, 2부터 i - 1까지 루프를 돌면서 나머지를 구한다.
         * 나머지가 0이 되면 나누어 떨어지는 것이므로 이 수는 소수가 된다.
         * 소수임이 판별되면 루프를 더 이상 돌 필요가 없으므로 break를 통해 ..
         * 빠져나온다.
         */
        for (j = 2; j < i; j++) {    
            if ( i % j == 0 )
                break;
        }
        /**
         * 위의 for 문을 빠져나올 수 있는 경우는 두가지이다.
         * 1. for 문이 다 돌았을 때, 즉 j가 i가 된 경우 ..
         * 2. break가 걸려서 빠져나올 때, 즉 j가 i보다 작은 경우 ..
         * 이 두 경우 중 소수임을 판별하기 위해 j와 i가 같은지 검사한다.
         */
        if ( i == j ) {    
            printf("소수는 %d\n", i);
        }
    }
}
이 작은숲 문서의 출처는 위키노트의 위키노트/C 언어 예제/소수 찾기 문서입니다.