Primes by Trial Division - C
15 April 2017
K&R C
No special instructions.
ANSI C
Compile with -D_ANSI (or /D "_ANSI" for MS-DOS style platforms).
AOS/VS
Compile with _XCALLOC/DEFINE.
BTOS C
Compile with -I<BTOSC> -D_XCALLOC -D_ANSI.
For n=10000, the large memory model is required. Add -ml to the compiler options and link accordingly.
IBM ILE C for AS/400
Use stdlib.h instead of malloc.h and compile with DEFINE('_ANSI').
Depending on your terminal keyboard, you may need to use the trigraphs ??( and ??) in place of square brackets.
Coherent 3.2
Rhapsody 5.x
Mac OS X 10.0–10.3
Compile with -I/usr/include/sys.
Manx Aztec C65
No long type: change format %lu to %u and all instances of long to int. Compile with -D_XCALLOC.
MetaWare High C for BTOS/CTOS
Compile with parameters -define _XCALLOC,_ANSI.
Minix 1.0 or 1.1 for IBM PC & XT
Create malloc.h with the following contents, then compile with -I. -D_V7.
/* calloc() */ char* calloc(n, siz) int n; int siz; { int i; char *p; p=(char*)malloc(n*siz); for(i=0; i<n*siz; i++) { p[i]=0; } return(p); }
Note: Minix 1.1 for Atari ST is based on Minix 1.3 code. See below for ST Minix.
Minix 1.2 for IBM PC, XT, or AT
Compile with -D_V7 -D_XCALLOC.
Minix 1.1 for Atari ST
Minix 1.3 for IBM PC, XT, or AT
Compile with -D_XCALLOC.
NEXTSTEP
Compile with -I/usr/include/bsd/sys.
U Waterloo SDG C2C for MS-DOS
Compile with D=_XCALLOC.
UTek W2.3 for Tektronix 6100
#include <sys/types.h> and use sys/systm.h instead of malloc.h.
VMS
Compile with /DEFINE=(_ANSI,_XCALLOC).
Gould G-NIX
SunOS 1.x & 2.x
MetroWerks C/C++ for BeOS 1.1d5 & 1.1d6
SCO Xenix SDS [ Lisa ]
Manx Aztec C 68k [ Amiga ]
IBM PC/IX 1.0 SDS [ IBM XT ]
IBM Xenix 1.0 SDS [ IBM AT ]
MetaWare High C [ IBM AOS ]
Mark Williams C [ Atari ST ]
Logical Systems C [ Transputer ]
Perihelion Helios C [ Transputer ]
Norcroft RISC OS ARM C [ Archimedes ]
Compile with -D_XCALLOC.
/* n primes */ #include <stdio.h> #ifndef _XCALLOC #include <malloc.h> #else extern char* calloc(); #endif #ifndef _V7 #define FORMAT "%lu\n" #else #define FORMAT "%D\n" #endif #ifdef _ANSI unsigned int patoi(char *str) { #else unsigned int patoi(str) char *str; { #endif int i; unsigned int res; i=0; res=0; while(str[i] != 0) { res=((res*10) + (str[i]-'0')); i++; } return(res); } #ifdef _ANSI int isprime(unsigned long n, unsigned long *primes) { #else int isprime(n, primes) unsigned long n; unsigned long *primes; { #endif int i; i=0; while(primes[i] > 0) { if(n % primes[i] == 0) { return(0); } i++; } return(1); } #ifdef _ANSI int main(int argc, char *argv[]) { #else int main(argc, argv) int argc; char **argv; { #endif unsigned int found, n; unsigned long count, *primes; found=0; count=2; n=patoi(argv[1]); primes=(unsigned long*)calloc(n, sizeof(long)); while(found < n) { if(isprime(count, primes)) { primes[found] = count; printf(FORMAT, count); found++; } count++; } return(0); }