The sieve of eratosthenes

Java

// Eratosthenes
// Another attempt at creating the Eratosthenes algorithm using Java.
/**
 * @author Nick Saika
 * @version 1.1
 */
import java.util.*;
public class Eratosthenes {
    public static ArrayList<Integer> numbers;
    public static ArrayList<Integer> primes = new ArrayList<Integer>();
    public static final int start = 2;
    public static int limit;
    public static void main(String[] args) {
	limit = Integer.parseInt(args[0]);
	numbers = new ArrayList<Integer>(limit);
	// Assign values from start to limit in arraylist numbers
	for (int i = 0; i < limit; i++) {
	    if ((i + start) > limit) break;
	    numbers.add(i, i + start);
	}
	// Add a number to the primes arraylist
	for (int i = 0; i < numbers.size(); i++) {
	    if (numbers.get(i) == 0) continue;
	    primes.add(numbers.get(i));
	    clearMultiplesOf(numbers.get(i));
	}
	for (int i = 0; i < primes.size(); i++) System.out.print(primes.get(i) + " ");
	    System.out.println();
    } // End of main(String[] args)
    public static void clearMultiplesOf(int n) {
	for (int m = 2; m < (limit / 2); m++) {
	    int multiple = n * m;
	    if (multiple == 0) continue;
		for (int i = 0; i < numbers.size(); i++) {
		    if (numbers.get(i) == multiple) numbers.set(i, 0);
		}
	    }
    } // End of clearMultiplesOf(int n)
}

back to Eratosthenes page

stats

It is Saturday May 17, 2008 11:00 am
This page served 1164 times
This page last modified: April 14, 2008 11:28 am
Your IP address is: 38.103.63.17
You are browsing using: CCBot/1.0 (+http://www.commoncrawl.org/bot.html)
You are browsing from: United States.
badcomputer.org's uptime: 11:00:03 up 23 days, 11:42, 0 users, load average: 0.00, 0.00, 0.00

local

home | unix stuff | dir2ogg | sneetchalizer | wmainfo | q&d guide to permissions | q&d guide to tar and gzip | code | MS rant | browser shootout | linux & iAudio X5 | photos | music | programming poetry | sieve of Eratosthenes | plea | rain | suffer | archive | about | recipes | compaqr3000 | sitemap

search

Google

credits

hacker emblem

This page, and all pages on this site were created and are maintained by Darren Kirby using valid XHTML 1.0 and CSS, and are ©copyright 2002 - 2008. The Penguin image was created by Tukka, and is used by permission. Inspiration for the look of this site was provided by Eric A. Meyer's CSS gallery. This website runs on Gentoo Linux. It is served by Apache. PHP and MySQL hold together the backend.

advertisement