Prime Number

#include <stdio.h> int is_prime(int n) { int m; for (m = 2; m*m <= n; m++) if (n % m == 0) // becareful, ! and ~ have very high priority, same as &, *, ++, -- return 0; return 1; } int next_prime(int n) { int m; while (++n) { for (m = 2; m*m <= n; m++) if (n % m == 0) break; // m will not increment by 1 if (m*m > n) // didn't find m that can devide n completely return n; } } int print_prime(int n) // print prime number within range 0 ~ n { int i, m; for (i = 0; i <= n; i++) { for (m = 2; m*m <= i; m++) if (i % m == 0) break; if (m*m > i) printf("%d ", i); } } int main() { int i; printf("%d \n", next_prime(31)); print_prime(30); }

Output:

37

0 1 2 3 5 7 11 13 17 19 23 29

page revision: 1, last edited: 16 Apr 2010 22:59