Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find number of values factors of two set of numbers
Suppose we have two arrays called nums1 and nums2. We have to find the number of values that satisfy the following conditions:
The elements in
nums1are the factors of the elements which are being selectedThe elements which are selected are factors of all elements of
nums2
So, if the input is like nums1 = [3,9] and nums2 = [27, 81], then the output will be 2 because the numbers are 9 and 27.
Algorithm
To solve this, we will follow these steps:
count := 0- For each number
iin range 1 to 100:- Check if all elements in
nums1divideievenly - Check if
idivides all elements innums2evenly - If both conditions are true, increment
count
- Check if all elements in
- Return
count
Example
Let us see the following implementation to get better understanding:
def solve(nums1, nums2):
count = 0
for i in range(1, 101):
flag = True
# Check if all elements in nums1 are factors of i
for j in nums1:
if i % j != 0:
flag = False
break
if flag:
# Check if i is a factor of all elements in nums2
for k in nums2:
if k % i != 0:
flag = False
break
if flag:
count += 1
return count
nums1 = [3, 9]
nums2 = [27, 81]
result = solve(nums1, nums2)
print(f"Number of valid values: {result}")
Number of valid values: 2
How It Works
For the example nums1 = [3, 9] and nums2 = [27, 81], the valid numbers are:
- Number 9: 9 % 3 = 0, 9 % 9 = 0, 27 % 9 = 0, 81 % 9 = 0 ?
- Number 27: 27 % 3 = 0, 27 % 9 = 0, 27 % 27 = 0, 81 % 27 = 0 ?
Complete Example with Verification
def solve(nums1, nums2):
count = 0
valid_numbers = []
for i in range(1, 101):
flag = True
# Check if all elements in nums1 are factors of i
for j in nums1:
if i % j != 0:
flag = False
break
if flag:
# Check if i is a factor of all elements in nums2
for k in nums2:
if k % i != 0:
flag = False
break
if flag:
count += 1
valid_numbers.append(i)
return count, valid_numbers
nums1 = [3, 9]
nums2 = [27, 81]
count, valid = solve(nums1, nums2)
print(f"Count: {count}")
print(f"Valid numbers: {valid}")
Count: 2 Valid numbers: [9, 27]
Conclusion
This algorithm finds numbers that are multiples of all elements in the first array and factors of all elements in the second array. The solution iterates through possible values and checks both conditions for each candidate number.
