/* Copyright (C) 2014 by Alexandru Cojocaru */ /* 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 3 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, see . */ #include #include #include typedef unsigned char uchar; static void setbit (uchar *b, int i) { b[i/8] |= 1 << (i%8); } static int getbit (uchar *b, int i) { return b[i/8] & (1 << (i%8)); } static uchar * makesieve (int n) { uchar *s = calloc (1, (n-1)/8+1); if (! s) assert (! "out of memory!!"); return s; } static void sundaramsieve (uchar *s, int n) { for (int j = 1; j < n; ++j) { for (int i = 1; i <= j; ++i) { if (i + j + 2*i*j > n) break; setbit (s, i + j + 2*i*j); } } } static void printsieve (uchar *s, int n) { printf ("%d\n", 2); for (int i = 1; i <= n; ++i) if (getbit (s, i) == 0) printf ("%d\n", i*2 + 1); } int main () { int n = 10000; n = (n-2-1)/2 + 1; uchar *s = makesieve (n+1); sundaramsieve (s, n); printsieve (s, n); }