One solution would be to change `LinkedList` to `ArrayList` and change the second loop that uses `j` variable to start from `i` as solutions 2 to `i` were already checked. This solution improved execution time from 0.67 sec to 0.09 sec: import java.util.LinkedList; import java.util.ArrayList; public class LinkedListEx { public static void main(String[] args) { long startTime = System.nanoTime(); List<Integer> ll = new ArrayList<Integer>(); for(int i = 2; i< 10000; i++) { ll.add(i); } int ls = ll.size(); for(int i=2; i < ls/2; i++) { // start from i for(int j =i; j<ls/2; j++) { int x = i*j; if(x<ls) ll.remove(new Integer(x)); } int y = i*i; if(y<ls) ll.remove(new Integer(y)); } long endTime = System.nanoTime(); double timeTakenToExecuteInSeconds = (double)(endTime - startTime)/1_000_000_000.0; System.out.println(ll); System.out.println(timeTakenToExecuteInSeconds); } }