You are viewing a single comment's thread. Return to all comments →
Java solution with sieve of eratosthenes for primes
public static List<Integer> waiter(List<Integer> number, int q) { Stack <Integer> supportStack = new Stack<>(); List<Integer> result = new ArrayList<>(); int max = getMax(number); List<Integer> primes = getPrimes(max, number.size()); for (int i = 0; i < q; i++) { int prime = primes.get(i); for (Integer n : number) { if (n % prime == 0) { result.add(n); } else { supportStack.push(n); } } number.clear(); while (!supportStack.isEmpty()) { number.add(supportStack.pop()); } } for (int i = number.size() - 1; i >= 0; i--) { result.add(number.get(i)); } return result; } private static int getMax(List<Integer> number) { int max = 0; for (Integer i : number) { if (i > max) { max = i; } } return max; } private static List<Integer> getPrimes (int n, int cap) { List<Integer> primes = new ArrayList<Integer>(); boolean[] prime = new boolean[n + 1]; for (int i = 0; i <= n; i++) { prime[i] = true; } for (int p = 2; p * p <= n; p++) { if (prime[p]) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } for (int i = 2; i <= n; i++) { if (prime[i] && primes.size() < cap) primes.add(i); } return primes; }
Seems like cookies are disabled on this browser, please enable them to open this website
Waiter
You are viewing a single comment's thread. Return to all comments →
Java solution with sieve of eratosthenes for primes