Determine can all number of array be made equal in C

Can all number of an array be made equal

Here, in this page we will discuss can all the number of an array be made equal in C.

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

can all number of array be made equal

Algorithm :

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

Code in C

//Write a program to check can all number of an array be made equal

#include <stdio.h>

int EqualNumbers(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;

       if (a[i] != a[0]) {
           return 0;
       }
    }

    return 1;
}

// Driver code
int main()
{
    int a[] = { 50, 75, 100 };

    int n = sizeof(a) / sizeof(a[0]);

    if (EqualNumbers(a, n))
       printf("Yes");
    else
       printf("No");

    return 0;
}

Output :

Yes

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription