File: primes.c
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright © 2024 pacman64
   5 
   6 Permission is hereby granted, free of charge, to any person obtaining a copy of
   7 this software and associated documentation files (the “Software”), to deal
   8 in the Software without restriction, including without limitation the rights to
   9 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  10 of the Software, and to permit persons to whom the Software is furnished to do
  11 so, subject to the following conditions:
  12 
  13 The above copyright notice and this permission notice shall be included in all
  14 copies or substantial portions of the Software.
  15 
  16 THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22 SOFTWARE.
  23 */
  24 
  25 /*
  26 You can build this command-line app by running
  27 
  28 cc -Wall -s -O2 -o ./primes ./primes.c -lm
  29 */
  30 
  31 #include <fcntl.h>
  32 #include <math.h>
  33 #include <stdbool.h>
  34 #include <stdint.h>
  35 #include <stdio.h>
  36 #include <stdlib.h>
  37 
  38 #ifdef _WIN32
  39 #include <windows.h>
  40 #endif
  41 
  42 
  43 // check if an odd number is a prime number; only works with odd values
  44 bool odd_is_prime(uint64_t n) {
  45     // uint64_t max = (uint64_t)sqrt((double)n);
  46     uint64_t max = (uint64_t)sqrtl(n);
  47     for (uint64_t div = 3; div <= max; div += 2) {
  48         if (n % div == 0) {
  49             return false;
  50         }
  51     }
  52     return true;
  53 }
  54 
  55 int main(int argc, char** argv) {
  56 #ifdef _WIN32
  57     // ensure output lines end in LF instead of CRLF on windows
  58     setmode(fileno(stdout), O_BINARY);
  59     setmode(fileno(stderr), O_BINARY);
  60 #endif
  61 
  62     uint64_t count = (uint64_t)1e6;
  63     if (argc > 1) {
  64         char* end;
  65         const int64_t n = strtol(argv[1], &end, 10);
  66         if (*end == 0) {
  67             count = n > 0 ? (uint64_t)n : 0;
  68         }
  69     }
  70 
  71     // 2 is the only even prime number, and the smallest one
  72     if (count > 0) {
  73         puts("2");
  74         count--;
  75     }
  76 
  77     for (uint64_t n = 3; count > 0; n += 2) {
  78         if (odd_is_prime(n)) {
  79             if (printf("%lu\n", (unsigned long)n) < 0) {
  80                 break;
  81             }
  82             count--;
  83         }
  84     }
  85 
  86     return 0;
  87 }