C++ program to determine can all numbers of an array be made equal

Check if all the numbers of array can be made equal

Here we will learn about C++ program to determine can all numbers of an array be made equal.

Let take an array arr[]. We need to check if all the numbers of an array can be  made equal to a particular number. In a single operation, any element of the array can be either multiplied by 2 or by 3. If it’s possible to make all the array elements equal with the given operation then print Yes else print No.

Example:

 Input: 3

50 75 100

Output: Yes ->{50 * 2 * 3, 75 * 2 * 2, 100 * 3} = {300, 300, 300}

Can all number of an array be made equalin C++

Keypoint

In this section we will learn about basic knowledge which we need to know before coding the above Program. So we must have knowledge of what is an array? 

What is an array?
An array is a data structure, it is collection of similar data elements which is stored at contiguous memory locations in which each data element can be accessed directly by only using its index number.

Algorithm

  1. Start traversing the array and check if the number is divisible by 2.
  2. If it is divisible, divide the array element by 2.
  3. Similarly, check if the array element is divisible by 3.
  4. If it is divisible, divide the array element by 3.
  5. Then, check the remaining elements with the first element of the array.
  6. If they are equal, the array can be made equal.
check-wether-all-elements-equal-array

C++ program to determine can all numbers of an array be made equal.

 // C++ program to check if all the numbers of an array are equal

#include <bits/stdc++.h>
using namespace std;
bool make_equal(int a[], int n){
for (int i = 0; i < n; i++) {

// Divide number by 2
while (a[i] % 2 == 0)
a[i] /= 2;

// Divide number by 3
while (a[i] % 3 == 0)
a[i] /= 3;
}

// Remaining numbers
for (int i = 1; i < n; i++) if (a[i] != a[0]) { return false; } return true; } int main(){ int a[15], n, i; cin>>n;
for(i=0; i<n; i++) cin>>a[i];

if (make_equal(a, n))
cout << "Yes";
else
cout << "No";

return 0;
}
output
   Enter number of entries: 3
    Enter Elements
    50
    75
    100
    yes