[ create a new paste ] login | about

Link: http://codepad.org/LHh5mx7w    [ raw code | output | fork ]

AaronMiller - C++, pasted on Jul 6:
#include <stdio.h>

#define MAX_PRIMES 100

unsigned int g_curPrimeIndex = 0;
unsigned int g_primes[MAX_PRIMES];

bool insertPrime(unsigned int n)
{
    /* Variables */
    unsigned int i;
    /* Quick exits */
    if (n<2) return false; /* Avoid an infinite loop */
    if (n==2) goto add_prime; /* 2 is an exception to the following */
    if (!(n&1)) return false; /* Aside from 2, prime numbers are never even */
    /* Check to see if the number is prime or not */
    for(i=0; /* initialize */
        g_primes[i]<(n>>1); /* insure that we don't perform redundant operations */
        i++) /* go to the next test value */
    {
        /* Check to see if this can divide evenly into the number */
        if ((n % g_primes[i]) == 0)
            /* If so, return false */
            return false;
        /* Avoid an out-of-bounds error (SIGSEGV) */
        if ((i+1)==MAX_PRIMES)
            /* Exit the loop */
            break;
    }
add_prime:
    /* The number appears to be prime, add it */
    g_primes[g_curPrimeIndex++] = n;
    /* Return */
    return true;
}

/* Main loop */
int main()
{
    unsigned int i=0;
    unsigned int n=1;
    while(g_curPrimeIndex < MAX_PRIMES)
    {
        if (insertPrime(n))
        {
            printf("%u\t", n);
            if(++i==8)
            {
                printf("\n");
                i=0;
            }
        }
        n++;
    }
    return 0;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
2	3	5	7	11	13	17	19	
23	29	31	37	41	43	47	53	
59	61	67	71	73	79	83	89	
97	101	103	107	109	113	127	131	
137	139	149	151	157	163	167	173	
179	181	191	193	197	199	211	223	
227	229	233	239	241	251	257	263	
269	271	277	281	283	293	307	311	
313	317	331	337	347	349	353	359	
367	373	379	383	389	397	401	409	
419	421	431	433	439	443	449	457	
461	463	467	479	487	491	499	503	
509	521	523	541	


Create a new paste based on this one


Comments: