소수 구하기
/* ============================================================================ Name : calc_primenum.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int *prime_list = NULL; int size = 0; int n = 0; int i, j; int found = 0; int root = 0; scanf("%d", &n); prime_list = malloc(sizeof(int) * n / 2); prime_list[0] = 2; prime_list[1] = 3; prime_list[2] = 5; size = 3; if (n > 0) { printf("%d\n", 2); } if (n > 1) { printf("%d\n", 3); } if (n > 2) { printf("%d\n", 5); } for ( i = 7 ; i < n ; i += 2 ) { if (i % 10 == 5) { continue; } root = sqrt(i); for ( j = 0 ; j < size ; j++ ) { if ( prime_list[j] > root ) { found = 0; break; } else if ( i % prime_list[j] == 0 ) { found = 1; break; } } if ( !found ) { prime_list[size++] = i; printf("%d\n", i); } } return 0; }
Discussion