중 1 수학시간에 학교에서 소수를 배우는데,
배우는 도중 문득 c언어 코드가 생각나서 집에와서 한번 만들어 보았습니다.
일단 소스를 보시죠.
Colored By Color Scripter™
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdio.h>
void main()
{
unsigned long long i, j, count = 1, s_max;
long sum = 0;
FILE *out;
out = fopen("a.txt", "w");
printf("어디까지의 소수를 출력하시겟습니까?");
scanf("%lld", &s_max);
for(i=1;i<=s_max;i++){
for(j=2;j<i;j++){
if((i%j)==0)
break;
}
if(i==j){
fprintf(out, "%lld\t", i);
printf("%lld\t", i);
count++;
if((count%8)==0)
fprintf(out, "\n");
printf("\n");
}
}
fprintf(out, "\n1부터 %lld 까지의 소수는 %lld개 입니다.", s_max, count);
printf("\n1부터 %lld 까지의 소수는 %lld개 입니다.", s_max, count);
fclose(out);
}
모든 숫자를 데입해서 소수를 찾는 형식으로 한 결과
역시 성공적이였습니다!!
하지만 더 큰 숫자를 하게 되면
이와 같이 매우 느린 속도로 연산을 하게 됩니다.
그래서!!
다시 만들게 되었습니다.
Colored By Color Scripter™
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<stdio.h>
int main()
{
FILE *out;
out = fopen("a.txt", "w");
unsigned int n, x, y, count=0;
printf("어디까지의 소수를 출력하시겟습니까?");
scanf("%d", &n);
x=1;
if(n>0){
fprintf(out, "2\t");
printf("2\t");
count++;
while(x+2<n) {
x+=2;
y=3;
while(y*y<x && x%y!=0){
y+=2;
}
if(y*y>x) {
fprintf(out, "%d\t", x);
printf("%d\t", x);
count++;
if((count%8)==0){
fprintf(out, "\n");
printf("\n");
}
}
}
fprintf(out, "\n1부터 %d 까지의 소수는 %d개 입니다.", n, count);
return 0;
}
}
이 방법은 2를 제외한 홀수들만 찾는 형식입니다.
과연 이 방법은 효과가 있을까요??
역시 확연한 차이를 보이네요
이상입니다^^
그림&동영상을 보시려면 http://blog.naver.com/0226daniel/220035729531 |