View Single Post
Old 02-12-2005, 08:32 AM   #10 (permalink)
FloydianOne
Crazy
 
Here is my C code, you can probably get a good idea on how to implement it in java.... I used Sieve algorithm.

Code:
#include <stdio.h>
    
    /* 
     * This allows us to change the number of primes to search
     * without modifying any code
     * For the l337:
     *   use #define to define TRUE and FALSE
     */
    #define MAX 3000

    int main() {
        int i,j;
        char primes[MAX];
        
        /* Set every number as being a prime, for ease of programming */
        for (i = 0; i < MAX; i++) {
            primes[i] = 0; /* 0 = False remember? */
        }
        
        /* 
         * Traverse the array, starting from 2, since 0 and 1 
         * are non-prime
         */
         
         for(i = 2; i < MAX; i++) {
	     primes[i] = 1;
	     
	     for(j = 2; j < i; j++) {
	     	if((i%j) == 0){
		    primes[i] = 0;
                                    }
        }
}
        /*
         * Print out the list of primes
         */
        /* the \n causes a newline to be printed */
        printf("The list of prime numbers from 1 to 3000 is as follows:\n");
        
        /* Traverse array and print out each number, followed by a
         * newline.
         * Accomplish this using printf("%d\n",i);
         * The %d tells printf that there is going to be a decimal
         * number after the comma.
         *
         * Remember that if primes[i] == TRUE, you must print out i
         * since i corresponds to the prime number, primes[i] defines
         * whether its a prime or not.
         */
        
        for(i = 1; i < MAX; i++){
		
		if(primes[i] == 1){
			printf("%d\n",i);
        	}
	}

        return 0;
        
    }
FloydianOne is offline  
 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43