• + 0 comments

    Python

    def get_primes_till_N(N):
        """
        Creates an array of primes till N.
        """
        if N < 2:
            return []
        
        # Initialize a list to track prime numbers
        is_prime = [True] * (N + 1)
        is_prime[0], is_prime[1] = False, False  # 0 and 1 are not primes
        
        # Apply the Sieve of Eratosthenes algorithm
        for start in range(2, int(N**0.5) + 1):
            if is_prime[start]:
                for multiple in range(start*start, N + 1, start):
                    is_prime[multiple] = False
        
        # Collect all prime numbers into a list
        primes = [num for num, prime in enumerate(is_prime) if prime]
        
        return primes
    
    # Create array of primes till 10001:
    primes = get_primes_till_N(10001)
    
    def waiter(number, q):
        answers = list()
        A = number[:]
    
        for i in range(q):
            # Finish iteration if A is empty
            if not A:
                break
            # Store values in pile B
            B = [num for num in A if num % primes[i] == 0][::-1]
            # Remove values from pile A
            A = [num for num in A if num % primes[i] != 0][::-1]
            # Add values of pile B to answers:
            answers += B[::-1]
            
        return answers + A[::-1]