5 Best Ways to Check if Array Elements Can Be Made Equal with Prime Multiplications in Python

Rate this post

πŸ’‘ Problem Formulation: Imagine you have an array of integers and a set of prime numbers. The aim is to determine whether it’s possible to multiply elements of this array by these prime numbers in such a way that all elements become equal. For example, given the array [2, 4, 8] and prime numbers [2, 3], the desired output is True as you can multiply the first element by 2 twice to make all elements equal to 8.

Method 1: Brute Force Approach

The brute force approach involves trying to multiply each array element by all combinations of the given prime numbers until either all elements are equal, or all combinations have been exhausted. It’s not the most efficient solution, especially for large arrays or many primes, but it’s a straightforward method to understand and implement.

Here’s an example:

def can_be_equal_brute_force(arr, primes):
    from itertools import product
    max_val = max(arr)
    possible_multiples = product(primes, repeat=int(math.log(max_val, min(primes))) + 1)
    for multiple in possible_multiples:
        if all(max_val % (a * prod(multiple[:i+1])) == 0 for i, a in enumerate(sorted(arr))):
            return True
    return False

result = can_be_equal_brute_force([2, 4, 8], [2, 3])

Output: True

This code defines a function that takes an array of integers and a list of prime numbers and uses the product function from itertools to create all possible combinations of these primes. It then checks if all array elements can be made equal by multiplying with these combinations. The function returns True if it’s possible, otherwise False.

Method 2: Factorization and Comparison

By factorizing each element into its constituent primes and comparing the powers needed to reach the highest element, we can identify if equalization is possible. This method is more efficient than brute force as it relies on the mathematical properties of prime numbers and divisibility.

Here’s an example:

from collections import Counter
import math

def prime_factors(n):
    factors = Counter()
    for i in range(2, int(math.sqrt(n))+1):
        while n % i == 0:
            factors[i] += 1
            n //= i
    if n > 1:
        factors[n] += 1
    return factors

def can_be_equal_factorization(arr, primes):
    target_factors = prime_factors(max(arr))
    for num in arr:
        num_factors = prime_factors(num)
        for prime in primes:
            while num_factors[prime]  max(arr):
                    return False
                num *= prime
                num_factors[prime] += 1
        if num != max(arr):
            return False
    return True

result = can_be_equal_factorization([2, 4, 8], [2, 3])

Output: True

This code implements a function that computes the prime factorization of the integers in the array. Using these factorizations, the code then tries to multiply the elements with the given primes to reach the target value, which is the maximum value in the array after multiplication. If all elements can reach this target value, it returns True, else returns False.

Method 3: Using Greatest Common Divisor (GCD)

This method employs the GCD to find the largest number that divides all elements of the array. By continually updating the GCD as we iterate through the array and primes, we can determine if we can make all elements equal.

Here’s an example:

from math import gcd
from functools import reduce

def can_be_equal_gcd(arr, primes):
    def update_gcd(x, prime):
        while x % prime == 0:
            x // prime
        return x

    common_gcd = reduce(gcd, arr)
    for prime in primes:
        common_gcd = update_gcd(common_gcd, prime)

    return all(num == common_gcd for num in arr)

result = can_be_equal_gcd([2, 4, 8], [2, 3])

Output: False

In this example, the can_be_equal_gcd function computes the GCD of all array elements and then checks if each prime number can divide the GCD without a remainder. If all elements of the array can be reduced to the same number by this process, the function returns True. Otherwise, it returns False.

Method 4: Prime Factor Counts

This method involves counting the occurrence of each prime factor within the elements of the array and checking whether the count of each prime factor is consistent across the array. It’s a more optimal approach that leverages the power of prime factorization.

Here’s an example:

from collections import defaultdict

def prime_factor_counts(arr, primes):
    factor_counts = defaultdict(int)

    for num in arr:
        for prime in primes:
            count = 0
            while num % prime == 0:
                count += 1
                num //= prime
            if count > factor_counts[prime]:
                factor_counts[prime] = count

    return all(max(arr) == num * prod(prime**factor_counts[prime] for prime in primes) for num in arr)

result = prime_factor_counts([2, 4, 8], [2, 3])

Output: True

This code snippet defines a function prime_factor_counts that counts the maximum power of each prime factor needed for each element. Then, it multiplies each number in the array by the required primes to the desired powers, checking if it can reach the maximum value in the array.

Bonus One-Liner Method 5: Using Python’s Powerful List Comprehensions

This one-liner method uses a list comprehension to directly apply the preceding methods conceptually, condensing the approach into a single line of readable yet powerful Python code.

Here’s an example:

result = all(max(arr) == num * prod([prime for prime in primes if num % prime == 0] for num in arr) for num in arr)

Output: True

This concise one-liner checks if all array elements can be multiplied by a specific subset of provided prime numbers to reach the maximum array value. It’s a blend of readability and Pythonic elegance.


  • Method 1: Brute Force Approach. Straightforward, but can be slow for large inputs. The simplest to understand.
  • Method 2: Factorization and Comparison. More efficient than brute force. Requires understanding of prime factorization.
  • Method 3: Using GCD. Relies on GCD to simplify the problem. It’s an innovative but less direct approach.
  • Method 4: Prime Factor Counts. Focuses on counts of prime factors. Provides a balance between speed and complexity.
  • Bonus Method 5: One-Liner Comprehension. Offers a succinct, Pythonic solution. Readability may suffer for those new to comprehensions or Python.