문제
1~1000 사이의 숫자 중에서 1과 그 자신 이외의 정수로 나누어지지 않는 소수를 구하는 것.
풀이
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
void main() | |
{ | |
int i, j, count = 1; | |
long sum = 0; | |
printf("1~1000 사이의 수 중에서 소수를 구하는 프로그램 \n"); | |
printf("%d\t", 1); | |
for (i = 1; i <= 1000; i++) { | |
for (j = 2; j < i; j++) { | |
if ((i % j) == 0) | |
break; | |
} | |
if (i == j) { | |
printf("%d\t", i); | |
count++; | |
if ((count % 8) == 0) | |
printf("\n"); | |
} | |
} | |
printf("\n1부터 1000 사이의 소수는 %d개이다. \n", count); | |
} |
해설
[12번 라인] 총 1~1000 숫자를 반복한다.
[13번 라인] 소수의 특징인 자기 자신을 제외한 1 ~ i-1수를 반복해서 나누며 소수인지 탐색한다.
[18번 라인] 소수일 경우 출력하고, count++로 소수의 갯수를 센다.
[22번 라인] 출력될 때 한 줄에 8개의 소수가 있으면 다음 줄로 넘긴다.
결과 화면
'Computer Science > Problem Solving' 카테고리의 다른 글
[18-알고리즘] 문자열 탐색(String Match) 라빈 카프 알고리즘(Rabin-Karp algorigm) (0) | 2018.06.17 |
---|---|
[18-알고리즘] 문자열 탐색(String Match) 소개 - Naive string match (0) | 2018.06.17 |
[알고리즘 문제풀이 전략]05 임의의 숫자 배수의 개수와 합 구하기 by C언어 (1) | 2017.08.19 |
[알고리즘 문제풀이 전략]04 피보나치 수열 byC언어 (0) | 2017.08.19 |
[알고리즘 문제풀이 전락]02 숫자 맞추기 byC언어 (0) | 2017.08.19 |