Created
January 23, 2013 17:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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