Skip to content

Instantly share code, notes, and snippets.

@priyankahdp
Created January 23, 2013 17:12
Show Gist options
  • Save priyankahdp/4610215 to your computer and use it in GitHub Desktop.
Save priyankahdp/4610215 to your computer and use it in GitHub Desktop.
LinkedListDemo for find the all prime numbers within the 0 and entered maximum number
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class LinkedListDemo {
public static void main(String[] args) {
System.out.println("Primes : ");
Scanner console = new Scanner(System.in);
System.out.println("Maximum Number ? ");
int max = console.nextInt();
List<Integer>primes=sleve(max);
System.out.println("upto " +max);
System.out.println(primes);
}
public static List<Integer> sleve(int max) {
List<Integer> primes = new LinkedList<Integer>();
List<Integer> numbers = new LinkedList<Integer>();
for (int i = 2; i <= max; i++) {
numbers.add(i);
}
while (!numbers.isEmpty()) {
int front = numbers.remove(0);
primes.add(front);
Iterator<Integer> itr = numbers.iterator();
while (itr.hasNext()) {
int current = itr.next();
if (current % front == 0) {
itr.remove();
}
}
}
return primes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment