Given an array of length N that contains only integers, the task is to print the special numbers of array. A number in this array is called Special number if it is divisible by at least one other number in the array.
Input : 1 2 3
Output : 2 3
Explanation : both 2 and 3 are divisible by 1.
Input : 2 3 4 6 8 9
Output : 4 6 8 9
Explanation : 2 and 3 are not divisible by any other element. Rest of the element are divisible by at-least 1 element. 6 is divisible by both 2 and 3, 4 divisible by 2, 8 divisible by 2 and 4 both, 9 divisible by 3.
Input : 3 5 7 11
Explanation : all elements are relatively prime so no special number.
A simple solution is to traverse through all elements, then check for every element if it is divisible by any other. Time complexity of this solution is O(n2)
Another solution that works better when there are many elements with not very big values. Store all array elements into hash and find out the max element in array then up-to max element find out the multiples of a given number then if multiple of array element is in hash then that number is divisible by at-least one element of array .To remove duplicate values we store the value into set because if array has 2, 3 and 6 then only 6 is divisible by at-least one element of array, both 2 and 3 divide 6 so 6 will be stored only one time.
# Python3 program to find special numbers
# in an array
import math as mt
# Function to find special numbers
def divisibilityCheck(arr, n):
# Storing all array elements in a hash
# and finding maximum element in array
s = dict()
max_ele = -10**9
for i in range(n):
s[arr[i]] = 1
# finding maximum element of array
max_ele = max(max_ele, arr[i])
# traversing array element and storing
# the array multiples that are present
# in s in res.
res = dict()
for i in range(n):
# Check for non-zero values only
if (arr[i] != 0):
# checking the factor of current element
for j in range(arr[i] * 2,
max_ele + 1, arr[i]):
# if factor is already part of
# array element then store it
if (j in s.keys()):
res[j] = 1
# displaying elements that are divisible
# by at least one other in array
for x in res:
print(x, end = ” “)
# Driver code
arr = [ 2, 3, 8, 6, 9, 10]
n = len(arr)
# This code is contributed by
# Mohit Kumar 29
9 10 8 6