Java 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 Java 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}

Input: 2

10 14

Output:no

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

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

  • Start span 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.

 

java program to check if all the numbers of array can be made equal

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

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

import java.util.*;
public class Main
{
    public static boolean make_equal(int d[], int m)
    {
        for (int i = 0; i < m; i++)
        {
             // Divide number by 2
            while (d[i] % 2 == 0)
                d[i] /= 2;

             // Divide number by 3
            while (d[i] % 3 == 0)
                d[i] /= 3;
        }
         // Remaining numbers
        for (int i = 1; i < m; i++)
            if (a[i] != a[0])
            {
                return false;
            }
        return true;
    }

    public static void main (String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int num,i;
        System.out.println("Enter the number of entries: ");
        num = sc.nextInt();
        int a[] = new int[num];
        System.out.println("Enter the elements: ");
        for(i=0; i<num; i++)
        {
            a[i] = sc.nextInt();
        }
        if (make_equal(a, num))
            System.out.println("Yes");
        else
            System.out.println("No");
    }

}