Python Program for Pairs such that one is a power multiple of other

Python Program for Pairs such that one is a power multiple of other

If you're looking for pairs of numbers in an array such that one number is a power multiple of another, then here's how you can approach this:

For each pair of numbers (x, y) in the array, x is a power multiple of y if the logarithm of x to the base y is an integer. This can be represented as:

logy​x=n where n is an integer.

Using this idea, you can create a Python program:

import math def is_power(x, y): # Check if y is 0 to avoid math domain error if y == 0: return False # Compute the logarithm of x with base y log_val = math.log(x, y) # Check if the log value is close to an integer return abs(log_val - round(log_val)) < 1e-10 def find_pairs(arr): n = len(arr) pairs = [] for i in range(n): for j in range(n): if i != j and is_power(arr[i], arr[j]): pairs.append((arr[i], arr[j])) return pairs # Test arr = [2, 4, 1, 16, 8, 64] print(find_pairs(arr)) # [(2, 4), (4, 2), (4, 16), (16, 4), (16, 64), (64, 16)] 

In the above program:

  • The is_power function checks if x is a power multiple of y.
  • The find_pairs function returns all pairs (x, y) such that x is a power multiple of y.
  • The test case checks for the pairs in the array [2, 4, 1, 16, 8, 64].

Note: This algorithm has a time complexity of O(n2) where n is the number of elements in the array.


More Tags

sdk code-behind performance-testing android-viewpager laravel-validation animated-gif postgresql-9.3 react-native-device-info jsr310 mocking

More Programming Guides

Other Guides

More Programming Examples