using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleRealTestApp1
{

    public class Program
    {
        //static List<string> letters = new List<string>() { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
        static List<long> _res = new List<long>();
        static long t, twos = 0, threes = 0, others = 0;
        static int BinSearch(List<long> arr, long x)
        {
            int l = 0, r = arr.Count() - 1, mid = 0;
            while (l < r - 1)
            {
                mid = (l + r) / 2;
                if (arr[mid] < x) l = mid;
                else r = mid;
            }
            return Math.Abs(arr[r] - x) >= Math.Abs(arr[l] - x) ? l : r;
        }
        static void m(int n)
        {
            //int div = 2;
            //while (n > 1)
            //{
            //    int k = 0;
            //    while (n % div == 0)
            //    {
            //        k++;
            //        n = n / div;
            //    }
            //    if (k > 0)
            //    {
            //        if (div == 2)
            //            twos += k;
            //        else if (div == 3)
            //            threes += k;
            //        else others += k;
            //        //if (n > 1) cout << "*";
            //    }
            //    if (div == 2) div++;
            //    else div += 2;
            //}
            while(n > 1)
            {
                if (n % 2 != 0 && n % 3 != 0) { others = 5; return; }
                while(n % 2 == 0)
                {
                    twos++;
                    n /= 2;
                }
                while(n % 3 == 0)
                {
                    threes++;
                    n /= 3;
                }
                if(n > 1) others = 5;
            }
        }
        static void Main(string[] args)
        {
            //long[] test = Console.ReadLine().Split(' ').Select(x => Convert.ToInt64(x)).ToArray();
            t = Convert.ToInt64(Console.ReadLine());
            for (int i = 0; i < t; i++)
            {
                int n = Convert.ToInt32(Console.ReadLine());
                int turns = 0;
                m(n);
                if(others > 0 || twos > threes)
                {
                    Console.WriteLine(-1);
                    twos = 0;
                    threes = 0;
                    others = 0;
                    continue;
                }
                while(threes > 0)
                {
                    if (twos == 0) { twos++; turns++; }
                    threes--;
                    twos--;
                    turns++;
                }
                Console.WriteLine(turns);
                twos = 0;
                threes = 0;
                others = 0;
            }
        }
    }
}
//long[] test = Console.ReadLine().Split(' ').Select(x => Convert.ToInt64(x)).ToArray();
//long n, x;
//long[] test = Console.ReadLine().Split(' ').Select(z => Convert.ToInt64(z)).ToArray();
//n = test[0];
//x = test[1];
//List<Tuple<long, long>> arr = new List<Tuple<long, long>>();
//long[] t = Console.ReadLine().Split(' ').Select(z => Convert.ToInt64(z)).ToArray();
//for (long i = 0; i < n; i++)
//{
//    arr.Add(new Tuple<long, long>(t[0], i));
//}
//arr = arr.OrderBy(z => z.Item1).ToList();
//for (int i = 0; i < n; i++)
//{
//    long value = x - arr[i].Item1;
//    if (value < arr[i].Item1) continue;
//    long l = i + 1, r = n - 1;
//}

//var Implementer = new ImplementerBuildingRoads(test[0], test[1]);
//for (int i = 0; i < Implementer.NumberOfRoads; i++)
//{
//    long[] t = Console.ReadLine().Split(' ').Select(x => Convert.ToInt64(x)).ToArray();
//    Implementer.towns[(int)t[0] - 1].Add(t[1] - 1);
//    Implementer.towns[(int)t[1] - 1].Add(t[0] - 1);
//}
////
//Implementer.BuildRoads();
////
//Console.WriteLine(Implementer.Result - 1);
//foreach (var item in Implementer.res)
//{
//    Console.WriteLine(item);
//}


using System;

namespace CodeForces
{
    class Program
    {
        static void Main(string[] args)
        {
            int testcases = int.Parse(Console.ReadLine());
            int[] answers = new int[testcases];
            int n;
            int i;

            for (int j = 0; j < testcases; j++)
            {
                n = int.Parse(Console.ReadLine());

                for (i = 0; n != 1; i++)
                {
                    if (n % 2 == 0)
                    {
                        if (n % 6 != 0)
                        {
                            answers[j] = -1;
                            break;
                        }

                        n /= 6;
                    }
                    else
                    {
                        n *= 2;
                    }
                }

                if (answers[j] != -1) answers[j] = i;
            }

            foreach (var a in answers)
            {
                Console.WriteLine(a);
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace CSharp
{
    public class C
    {
        public static void Main()
        {
           int t = int.Parse(Console.ReadLine());

           for(int u=0;u<t;u++){
              int n = int.Parse(Console.ReadLine());
              int ans = 0;
              while(true){
                if(n==1){
                  break;
                }else if(n<1){
                  ans = -1;
                  break;
                }
                ans++;
                if(n%6==0){
                  n = n/6;
                }else{
                  n = n * 2;
                }
              }
              Console.WriteLine(ans);

           }
        }
    }
}


using System;

namespace multi2div6
{
    class Program
    {
        static void Main()
        {
            int a;
            string b;
            string val;
            ulong n;
            ulong z = 0;
            int x = 0;
            int y = 0;
            Console.WriteLine("Enter the number of test cases");
            b = Console.ReadLine();
            a = Convert.ToInt32(b);
            for (int i = 0; i < a; i++)
            {
                y = 0;
                z = 0;
                x = 0;
                Console.WriteLine("Enter the number");
                val = Console.ReadLine();
                n = Convert.ToUInt64(val);

                while (z != 1)
                {
                    if (z == 0)
                        z = n;
                    x = x + 1;
                    if (z % 6 == 0)
                        z = z / 6;
                    else
                    {
                        if (z % 3 == 0 && z % 2 != 0)
                            z = z * 2;
                        else if ((z % 3 != 0 && z % 2 != 0) || (z % 3 != 0 && z % 2 == 0))
                        {
                            Console.WriteLine("-1");
                            y = 1;
                            z = 1;
                        }

                    }
                }
                if (y == 0)
                    Console.WriteLine(x);

            }
        }
    }
}


using System;

namespace multi2div6
{
    class Program
    {
        static void Main()
        {
            int a;
            string b;
            string val;
            ulong n;
            ulong z = 0;
            int x = 0;
            int y = 0;

            b = Console.ReadLine();
            a = Convert.ToInt32(b);
            for (int i = 0; i < a; i++)
            {
                y = 0;
                z = 0;
                x = 0;

                val = Console.ReadLine();
                n = Convert.ToUInt64(val);

                while (z != 1)
                {
                    if(n==1)
                    break;
                    if (z == 0)
                        z = n;
                    x = x + 1;
                    if (z % 6 == 0)
                        z = z / 6;
                    else
                    {
                        if (z % 3 == 0 && z % 2 != 0)
                            z = z * 2;
                        else if ((z % 3 != 0 && z % 2 != 0) || (z % 3 != 0 && z % 2 == 0))
                        {
                            Console.WriteLine("-1");
                            y = 1;
                            z = 1;
                        }

                    }
                }
                if (y == 0)
                    Console.WriteLine(x);

            }
        }
    }
}


using System;

namespace multi2div6
{
    class Program
    {
        static void Main()
        {
            int a;
            string b;
            string val;
            ulong n;
            ulong z = 0;
            int x = 0;
            int y = 0;

            b = Console.ReadLine();
            a = Convert.ToInt32(b);
            for (int i = 0; i < a; i++)
            {
                y = 0;
                z = 0;
                x = 0;

                val = Console.ReadLine();
                n = Convert.ToUInt64(val);

                while (z != 1)
                {
                    if (z == 0)
                        z = n;
                    x = x + 1;
                    if (z % 6 == 0)
                        z = z / 6;
                    else
                    {
                        if (z % 3 == 0 && z % 2 != 0)
                            z = z * 2;
                        else if ((z % 3 != 0 && z % 2 != 0) || (z % 3 != 0 && z % 2 == 0))
                        {
                            Console.WriteLine("-1");
                            y = 1;
                            z = 1;
                        }

                    }
                }
                if (y == 0)
                    Console.WriteLine(x);

            }
        }
    }
}


using System;

namespace multi2div6
{
    class Program
    {
        static void Main()
        {
            string val;
            ulong n;
            ulong z = 0;
            int x = 0;
            int y = 0;
            Console.WriteLine("Enter the number");
            val = Console.ReadLine();
            n = Convert.ToUInt64(val);

            while (z != 1)
            {
                if (z == 0)
                    z = n;
                x = x + 1;
                if (z % 6 == 0)
                    z = z / 6;
                else
                {
                    if (z % 3 == 0 && z % 2 != 0)
                        z = z * 2;
                    else if ((z % 3 != 0 && z % 2 != 0) || (z % 3 != 0 && z % 2 == 0))
                    {
                        Console.WriteLine("-1");
                        y = 1;
                        z = 1;
                    }

                }
            }
            if (y == 0)
                Console.WriteLine("The number of independent test cases are " +x);

        }
    }
}


using System;

class Program {
    static void Main() {
        int count = int.Parse(Console.ReadLine());

        for (int c = 0; c < count; c++) {
            long n = long.Parse(Console.ReadLine());
            int ans = 0;
            while (n != 1) {
                if (n % 6 == 0) {
                    n /= 6;
                } else {
                    n *= 2;
                }
                ans++;
                if (n < 1) {
                    ans = -1;
                    break;
                }
            }
            Console.WriteLine(ans);
        }

        Console.ReadKey();
    }
}


using System;

class Program {
    static void Main() {
        int count = int.Parse(Console.ReadLine());

        for (int c = 0; c < count; c++) {
            int n = int.Parse(Console.ReadLine());
            int ans = 0;
            while (n != 1) {
                if (n % 6 == 0) {
                    n /= 6;
                } else {
                    n *= 2;
                }
                ans++;
                if (n < 1) {
                    ans = -1;
                    break;
                }
            }
            Console.WriteLine("ans = "+ans);
        }
    }
}


using System;

class Program {
    static void Main() {
        int count = int.Parse(Console.ReadLine());

        for (int c = 0; c < count; c++) {
            long n = long.Parse(Console.ReadLine());
            int ans = 0;
            while (n != 1) {
                if (n % 6 == 0) {
                    n /= 6;
                } else {
                    n *= 2;
                }
                ans++;
                if (n < 1) {
                    ans = -1;
                    break;
                }
            }
            Console.WriteLine("ans = "+ans);
        }
    }
}


using System;

class Program {
    static void Main() {
        int count = int.Parse(Console.ReadLine());

        for (int c = 0; c < count; c++) {
            long n = long.Parse(Console.ReadLine());
            int ans = 0;
            while (n != 1) {
                if (n % 6 == 0) {
                    n /= 6;
                } else {
                    n *= 2;
                }
                ans++;
                if (n < 1) {
                    ans = -1;
                    break;
                }
            }
            Console.WriteLine(ans);
        }
    }
}


/* Date: 28.06.2020 *  Time: 21:45 */
//

using System;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
#if (!ONLINE_JUDGE)
        public static StreamReader sr = new StreamReader ("C:\\TRR\\2020\\Task\\07 Codeforces\\048\\B.TXT");
        public static StreamWriter sw = new StreamWriter ("C:\\TRR\\2020\\Task\\07 Codeforces\\048\\OUTPUT.OUT");
#endif

        static void Main(string[] args)
        {
			NumberFormatInfo nfi = NumberFormatInfo.InvariantInfo;

			int q;

#if (ONLINE_JUDGE)
			q = int.Parse (Console.ReadLine ());
#else
			q = int.Parse(sr.ReadLine());
			sw.WriteLine("*** test = " + q);
#endif

			for (int __q = 0; __q < q; __q++)
			{
				//string s;
				int n;

#if (ONLINE_JUDGE)
				n = int.Parse (Console.ReadLine ());
#else
				n = int.Parse (sr.ReadLine());
#endif

				int m = 0, k = 0;
				while (n > 1 && n % 3 == 0)
                {
					n /= 3; k++;
                }
				while (n > 1 && n % 2 == 0)
				{
					n /= 2; m++;
				}

				if (n > 1 || m > k)
					k = -1;
				else
					k = k + k - m;
#if (ONLINE_JUDGE)
				Console.WriteLine (k);
#else
				sw.WriteLine(k);
#endif
			}
#if (!ONLINE_JUDGE)
			sw.Close();
#endif
		}
	}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            for (int i = 0; i < t; i++)
            {
                long n = long.Parse(Console.ReadLine());
                if (n == 1)
                    Console.WriteLine("0");
                else
                {
                    long copyn = n;
                    int c3, c2;
                    c3 = c2 = 0;
                    while (copyn % 3 == 0)
                    {
                        c3++;
                        copyn /= 3;
                    }
                    copyn = n;
                    while (copyn % 2 == 0)
                    {
                        c2++;
                        copyn /= 2;
                    }
                    if (c3 < c2 || Math.Pow(3, c3) * Math.Pow(2, c2) != n)
                        Console.WriteLine("-1");
                    else
                        Console.WriteLine(c3 - c2 + c3);
                }
            }
            Console.ReadLine();
        }
    }
}


using System;

namespace _123
{
    class Program
    {
        static void Main(string[] args)
        {
            int ni = Int32.Parse(Console.ReadLine());
            int[] n = new int[ni];

            for (int i = 0; i < n.Length; i++)
            {
                n[i] = Int32.Parse(Console.ReadLine());
            }

            int[] ns = new int[ni];

            for (int i = 0; i < n.Length; i++)
            {
                while (true)
                {

                    if (ns[i] == -1 || n[i] == 1)
                    {
                        if (ns[i] == -1)
                        {
                            ns[i] = -1;
                        }

                        break;
                    }

                    if ((n[i] % 3) != 0)
                    {
                        ns[i] = -1;
                        break;
                    }

                    if ((n[i] % 6) == 0)
                    {
                        n[i] /= 6;
                    }
                    else n[i] *= 2;

                    ns[i]++;
                }
            }

            foreach (int i in ns)
            {
                Console.WriteLine(i);
            }
        }
    }
}


using System;

namespace _123
{
    class Program
    {
        static void Main(string[] args)
        {
            int ni = Int32.Parse(Console.ReadLine());
            int[] n = new int[ni];

            for (int i = 0; i < n.Length; i++)
            {
                n[i] = Int32.Parse(Console.ReadLine());
            }

            Console.WriteLine("Input done");

            int[] ns = new int[ni];

            Console.WriteLine("Calc");

            for (int i = 0; i < n.Length; i++)
            {
                while (true)
                {

                    if (ns[i] == -1 || n[i] == 1)
                    {
                        if (ns[i] == -1)
                        {
                            ns[i] = -1;
                        }

                        break;
                    }

                    if ((n[i] % 3) != 0)
                    {
                        ns[i] = -1;
                        break;
                    }

                    if ((n[i] % 6) == 0)
                    {
                        n[i] /= 6;
                    }
                    else n[i] *= 2;

                    ns[i]++;
                }
            }

            foreach (int i in ns)
            {
                Console.WriteLine(i);
            }
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Codeforces
{

    class Program
    {
        static void Main(string[] args)
        {
            var t = Convert.ToInt32(Console.ReadLine());
            int n;
            int k = 0;
            for (int i = 0; i < t; i++)
            {
                n = Convert.ToInt32(Console.ReadLine());
                if(n == 1)
                {
                    Console.WriteLine("-1");
                    continue;
                }
                k = 0;
                while(n%3 == 0)
                {
                    if (n % 6 == 0) n /= 6;
                    else
                    {
                        n *= 2;
                        n /= 6;
                    }
                    k++;
                }
                if (n == 1) Console.WriteLine(k);
                else Console.WriteLine(-1);
            }
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Codeforces
{

    class Program
    {
        static void Main(string[] args)
        {
            var t = Convert.ToInt32(Console.ReadLine());
            int n;
            int k = 0;
            for (int i = 0; i < t; i++)
            {
                n = Convert.ToInt32(Console.ReadLine());
                if(n == 1)
                {
                    Console.WriteLine("0");
                    continue;
                }
                k = 0;
                while(n%3 == 0)
                {
                    if (n % 6 == 0) n /= 6;
                    else
                    {
                        n *= 2;
                    }
                    k++;
                }
                if (n == 1) Console.WriteLine(k);
                else Console.WriteLine(-1);
            }
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Codeforces
{

    class Program
    {
        static void Main(string[] args)
        {
            var t = Convert.ToInt32(Console.ReadLine());
            int n;
            int k = 0;
            for (int i = 0; i < t; i++)
            {
                n = Convert.ToInt32(Console.ReadLine());
                if(n == 1)
                {
                    Console.WriteLine("0");
                    continue;
                }
                k = 0;
                while(n%3 == 0)
                {
                    if (n % 6 == 0) n /= 6;
                    else
                    {
                        n *= 2;
                        n /= 6;
                    }
                    k++;
                }
                if (n == 1) Console.WriteLine(k);
                else Console.WriteLine(-1);
            }
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Codeforces
{

    class Program
    {
        static void Main(string[] args)
        {
            var t = Convert.ToInt32(Console.ReadLine());
            int n;
            int k = 0;
            for (int i = 0; i < t; i++)
            {
                n = Convert.ToInt32(Console.ReadLine());
                k = 0;
                while(n%3 == 0)
                {
                    if (n % 6 == 0) n /= 6;
                    else
                    {
                        n *= 2;
                        n /= 6;
                    }
                    k++;
                }
                if (n == 1) Console.WriteLine(k);
                else Console.WriteLine(-1);
            }
        }
    }
}


//Template by _Trung_Nguyen
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System.IO;

using Libraries;
using Libraries.IO;
using Libraries.Collections;

namespace Codeforces
{
	public class sample
	{
		private static bool root6(int n, out int log2, out int log3)
		{
			log2 = 0;
			log3 = 0;
			while (n % 2 == 0)
			{
				n /= 2;
				++log2;
			}
			while (n % 3 == 0)
			{
				n /= 3;
				++log3;
			}
			return n == 1;
		}
		private static int solution()
		{
			int t = cin.ReadInt32();

			while (t-->0)
			{
				int n = cin.ReadInt32();
				int log2;
				int log3;
				bool a = root6(n, out log2, out log3);
				if (!a)
				{
					cout.WriteLine("-1");
					continue;
				}
				if (log2 > log3)
				{
					cout.WriteLine("-1");
					continue;
				}

				cout.WriteLine((log3 - log2) + log3);

			}

			return 0;
		}

//===============Prewritten code======================
		private static istream cin = new istream(Console.OpenStandardInput());
		private static ostream cout = new ostream(Console.OpenStandardOutput());
		private static ostream cerr = new ostream(Console.OpenStandardError());
		private static ostream clog = new ostream(Console.OpenStandardError(), true);

		public static int Main()
		{
			try
			{
				int returnValue = solution();
				cout.Flush();
				cerr.Flush();
				return returnValue;
			}
			catch (Exception e)
			{
				Console.WriteLine(e.ToString());
				return -1;
			}
		}
	}
}

namespace Libraries.IO
{
	public class istream : IDisposable
	{
		private BufferedStream buffer;
		private StreamReader reader;
		private Queue<string> words = new Queue<string>();
		private void getWords()
		{
			while (words.Count == 0)
			{
				string [] temp = reader.ReadLine().Split();
				foreach (var str in temp)
				{
					if (str.Length == 0) continue;
					words.Enqueue(str);
				}
			}
		}
		public istream(Stream istr)
		{
			buffer = new BufferedStream(istr);
			reader = new StreamReader(buffer);
		}
		public int Peek()
		{
			return reader.Peek();
		}
		public int Read()
		{
			return reader.Read();
		}
		public string ReadLine()
		{
			return reader.ReadLine();
		}
		public int [] ReadInt32Array()
		{
			return reader.ReadLine().Split().Select(x => Convert.ToInt32(x)).ToArray();
		}
		public long [] ReadInt64Array()
		{
			return reader.ReadLine().Split().Select(x => Convert.ToInt64(x)).ToArray();
		}
		public string [] ReadStringArray()
		{
			return reader.ReadLine().Split();
		}
		public int ReadInt32()
		{
			getWords();
			return Convert.ToInt32(words.Dequeue());
		}
		public long ReadInt64()
		{
			getWords();
			return Convert.ToInt64(words.Dequeue());
		}
		public string ReadString()
		{
			getWords();
			return words.Dequeue();
		}
		public void Dispose()
		{
			reader.Dispose();
			buffer.Dispose();
		}
	}
	public class ostream : IDisposable
	{
		private BufferedStream buffer;
		private StreamWriter writer;
		public ostream(Stream ostr, bool autoflush = false)
		{
			buffer = new BufferedStream(ostr);
			writer = new StreamWriter(buffer);
			writer.AutoFlush = autoflush;
		}
		public void Write(string format, params object[] args)
		{
			writer.Write(format, args);
		}
		public void Write<T>(T value)
		{
			writer.Write(value);
		}
		public void Write<T>(T [] arr, string sep)
		{
			string fmt = "{0}" + sep;
			foreach (var x in arr) writer.Write(fmt, x);
		}
		public void WriteLine(string format, params object[] args)
		{
			writer.WriteLine(format, args);
		}
		public void WriteLine<T>(T value)
		{
			writer.WriteLine(value);
		}
		public void WriteLine<T>(IEnumerable<T> arr, string sep)
		{
			string fmt = "{0}" + sep;
			foreach (var x in arr) writer.Write(fmt, x);
			writer.WriteLine();
		}
		public void WriteLine<T>(IEnumerable<T> arr, string sep, Func<T, T> funct)
		{
			string fmt = "{0}" + sep;
			foreach (var x in arr) writer.Write(fmt, funct(x));
			writer.WriteLine();
		}
		public void WriteLine()
		{
			writer.WriteLine();
		}
		public void Flush()
		{
			writer.Flush();
		}
		public void Dispose()
		{
			writer.Dispose();
			buffer.Dispose();
		}
	}
}
namespace Libraries
{
	public class Utilities
	{
		public static void Swap<T>(ref T x, ref T y)
		{
			T temp = y;
			y = x;
			x = temp;
		}
	}

	public static class Arrays
	{
		private static T Inc<T>(ref T value)
		{
			dynamic temp = value;
			dynamic temp2 = temp;
			value = ++temp2;
			return temp++;
		}
		public static IEnumerable<T> FillDefault<T>(int size) where T : new()
		{
			for (int i = 0; i < size; ++i) yield return new T();
		}
		public static IEnumerable<T> Fill<T>(int size, T value)
		{
			for (int i = 0; i < size; ++i) yield return value;
		}
		public static IEnumerable<T> Fill<T>(int size, Func<T> funct)
		{
			for (int i = 0; i < size; ++i) yield return funct();
		}
		public static IEnumerable<T> Iota<T>(int size, T init)
		{
			for (int i = 0; i < size; ++i) yield return Inc(ref init);
		}
		public static T First<T> (this IList<T> container)
		{
			if (container.Count == 0) throw new InvalidOperationException("The container is empty");
			return container[0];
		}
		public static T Last<T> (this IList<T> container)
		{
			if (container.Count == 0) throw new InvalidOperationException("The container is empty");
			return container[container.Count - 1];
		}
		public static void RemoveLast<T> (this IList<T> container)
		{
			if (container.Count == 0) throw new InvalidOperationException("The container is empty");
			container.RemoveAt(container.Count - 1);
		}
	}
}

namespace Libraries.Collections
{
	class PriorityQueue<T> where T : IComparable
	{
	    private List<T> list;
	    public int Count { get { return list.Count; } }
	    public readonly bool IsDescending;

	    public PriorityQueue(bool isdesc = true)
	    {
	        list = new List<T>();
	        IsDescending = isdesc;
	    }

	    public PriorityQueue(int capacity, bool isdesc = true)
	    {
	        list = new List<T>(capacity);
	        IsDescending = isdesc;
	    }

	    public PriorityQueue(IEnumerable<T> collection, bool isdesc = true)
	        : this()
	    {
	        IsDescending = isdesc;
	        foreach (var item in collection)
	            Enqueue(item);
	    }

	    public void Enqueue(T x)
	    {
	        list.Add(x);
	        int i = Count - 1;

	        while (i > 0)
	        {
	            int p = (i - 1) / 2;
	            if ((IsDescending ? -1 : 1) * list[p].CompareTo(x) <= 0) break;

	            list[i] = list[p];
	            i = p;
	        }

	        if (Count > 0) list[i] = x;
	    }

	    public T Dequeue()
	    {
	        T target = Peek();
	        T root = list[Count - 1];
	        list.RemoveAt(Count - 1);

	        int i = 0;
	        while (i * 2 + 1 < Count)
	        {
	            int a = i * 2 + 1;
	            int b = i * 2 + 2;
	            int c = b < Count && (IsDescending ? -1 : 1) * list[b].CompareTo(list[a]) < 0 ? b : a;

	            if ((IsDescending ? -1 : 1) * list[c].CompareTo(root) >= 0) break;
	            list[i] = list[c];
	            i = c;
	        }

	        if (Count > 0) list[i] = root;
	        return target;
	    }

	    public T Peek()
	    {
	        if (Count == 0) throw new InvalidOperationException("Queue is empty.");
	        return list[0];
	    }

	    public void Clear()
	    {
	        list.Clear();
	    }
	}
    internal class DequeUtility
    {
        public static int ClosestPowerOfTwoGreaterThan(int x)
        {
            x--;
            x |= (x >> 1);
            x |= (x >> 2);
            x |= (x >> 4);
            x |= (x >> 8);
            x |= (x >> 16);
            return (x+1);
        }

        public static int Count<TSource>(IEnumerable<TSource> source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            ICollection<TSource> genericCollection = source as ICollection<TSource>;
            if (genericCollection != null)
            {
                return genericCollection.Count;
            }

            ICollection nonGenericCollection = source as ICollection;
            if (nonGenericCollection != null)
            {
                return nonGenericCollection.Count;
            }

            checked
            {
                int count = 0;
                using (var iterator = source.GetEnumerator())
                {
                    while (iterator.MoveNext())
                    {
                        count++;
                    }
                }
                return count;
            }
        }
    }

    public class Deque<T> : IList<T>
    {
        private const int defaultCapacity = 16;

        private int startOffset;

        private T[] buffer;

        public Deque() : this(defaultCapacity) { }

        public Deque(int capacity)
        {
            if (capacity < 0)
            {
                throw new ArgumentOutOfRangeException(
                    "capacity", "capacity is less than 0.");
            }

            this.Capacity = capacity;
        }

        public Deque(IEnumerable<T> collection)
            : this(DequeUtility.Count(collection))
        {
            InsertRange(0, collection);
        }

        private int capacityClosestPowerOfTwoMinusOne;

        public int Capacity
        {
            get
            {
                return buffer.Length;
            }

            set
            {
                if (value < 0)
                {
                    throw new ArgumentOutOfRangeException(
                        "value",
                        "Capacity is less than 0.");
                }
                else if (value < this.Count)
                {
                    throw new InvalidOperationException(
                        "Capacity cannot be set to a value less than Count");
                }
                else if (null != buffer && value == buffer.Length)
                {
                    return;
                }

                int powOfTwo = DequeUtility.ClosestPowerOfTwoGreaterThan(value);

                value = powOfTwo;

                T[] newBuffer = new T[value];
                this.CopyTo(newBuffer, 0);

                buffer = newBuffer;
                startOffset = 0;
                this.capacityClosestPowerOfTwoMinusOne = powOfTwo - 1;
            }
        }

        public bool IsFull
        {
            get { return this.Count == this.Capacity; }
        }

        public bool IsEmpty
        {
            get { return 0 == this.Count; }
        }

        private void ensureCapacityFor(int numElements)
        {
            if (this.Count + numElements > this.Capacity)
            {
                this.Capacity = this.Count + numElements;
            }
        }

        private int toBufferIndex(int index)
        {
            int bufferIndex;

            bufferIndex = (index + this.startOffset)
                & this.capacityClosestPowerOfTwoMinusOne;

            return bufferIndex;
        }

        private void checkIndexOutOfRange(int index)
        {
            if (index >= this.Count)
            {
                throw new IndexOutOfRangeException(
                    "The supplied index is greater than the Count");
            }
        }

        private static void checkArgumentsOutOfRange(
            int length,
            int offset,
            int count)
        {
            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException(
                    "offset", "Invalid offset " + offset);
            }

            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(
                    "count", "Invalid count " + count);
            }

            if (length - offset < count)
            {
                throw new ArgumentException(
                    String.Format(
                    "Invalid offset ({0}) or count + ({1}) "
                    + "for source length {2}",
                    offset, count, length));
            }
        }

        private int shiftStartOffset(int value)
        {
            this.startOffset = toBufferIndex(value);

            return this.startOffset;
        }

        private int preShiftStartOffset(int value)
        {
            int offset = this.startOffset;
            this.shiftStartOffset(value);
            return offset;
        }

        private int postShiftStartOffset(int value)
        {
            return shiftStartOffset(value);
        }

        #region IEnumerable

        public IEnumerator<T> GetEnumerator()
        {
            if (this.startOffset + this.Count > this.Capacity)
            {
                for (int i = this.startOffset; i < this.Capacity; i++)
                {
                    yield return buffer[i];
                }

                int endIndex = toBufferIndex(this.Count);
                for (int i = 0; i < endIndex; i++)
                {
                    yield return buffer[i];
                }
            }
            else
            {
                int endIndex = this.startOffset + this.Count;
                for (int i = this.startOffset; i < endIndex; i++)
                {
                    yield return buffer[i];
                }
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
        #endregion

        #region ICollection

        bool ICollection<T>.IsReadOnly
        {
            get { return false; }
        }

        public int Count
        {
            get;
            private set;
        }

        private void incrementCount(int value)
        {
            this.Count = this.Count + value;
        }

        private void decrementCount(int value)
        {
            this.Count = Math.Max(this.Count - value, 0);
        }

        public void Add(T item)
        {
            AddLast(item);
        }

        private void ClearBuffer(int logicalIndex, int length)
        {
            int offset = toBufferIndex(logicalIndex);
            if (offset + length > this.Capacity)
            {
                int len = this.Capacity - offset;
                Array.Clear(this.buffer, offset, len);

                len = toBufferIndex(logicalIndex + length);
                Array.Clear(this.buffer, 0, len);
            }
            else
            {
                Array.Clear(this.buffer, offset, length);
            }
        }

        public void Clear()
        {
            if (this.Count > 0)
            {
                ClearBuffer(0, this.Count);
            }
            this.Count = 0;
            this.startOffset = 0;
        }

        public bool Contains(T item)
        {
            return this.IndexOf(item) != -1;
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            if (null == array)
            {
                throw new ArgumentNullException("array", "Array is null");
            }

            if (null == this.buffer)
            {
                return;
            }

            checkArgumentsOutOfRange(array.Length, arrayIndex, this.Count);

            if (0 != this.startOffset
                && this.startOffset + this.Count >= this.Capacity)
            {
                int lengthFromStart = this.Capacity - this.startOffset;
                int lengthFromEnd = this.Count - lengthFromStart;

                Array.Copy(
                    buffer, this.startOffset, array, 0, lengthFromStart);

                Array.Copy(
                    buffer, 0, array, lengthFromStart, lengthFromEnd);
            }
            else
            {
                Array.Copy(
                    buffer, this.startOffset, array, 0, Count);
            }
        }

        public bool Remove(T item)
        {
            bool result = true;
            int index = IndexOf(item);

            if (-1 == index)
            {
                result = false;
            }
            else
            {
                RemoveAt(index);
            }

            return result;
        }

        #endregion

        #region List<T>

        public T this[int index]
        {
            get
            {
                return this.Get(index);
            }

            set
            {
                this.Set(index, value);
            }
        }

        public void Insert(int index, T item)
        {
            ensureCapacityFor(1);

            if (index == 0)
            {
                AddFirst(item);
                return;
            }
            else if (index == Count)
            {
                AddLast(item);
                return;
            }

            InsertRange(index, new[] { item });
        }

        public int IndexOf(T item)
        {
            int index = 0;
            foreach (var myItem in this)
            {
                if (myItem.Equals(item))
                {
                    break;
                }
                ++index;
            }

            if (index == this.Count)
            {
                index = -1;
            }

            return index;
        }

        public void RemoveAt(int index)
        {
            if (index == 0)
            {
                RemoveFirst();
                return;
            }
            else if (index == Count - 1)
            {
                RemoveLast();
                return;
            }

            RemoveRange(index, 1);
        }
        #endregion

        public void AddFirst(T item)
        {
            ensureCapacityFor(1);
            buffer[postShiftStartOffset(-1)] = item;
            incrementCount(1);
        }

        public void AddLast(T item)
        {
            ensureCapacityFor(1);
            buffer[toBufferIndex(this.Count)] = item;
            incrementCount(1);
        }

        public T RemoveFirst()
        {
            if (this.IsEmpty)
            {
                throw new InvalidOperationException("The Deque is empty");
            }

            T result = buffer[this.startOffset];
            buffer[preShiftStartOffset(1)] = default(T);
            decrementCount(1);
            return result;
        }

        public T RemoveLast()
        {
            if (this.IsEmpty)
            {
                throw new InvalidOperationException("The Deque is empty");
            }

            decrementCount(1);
            int endIndex = toBufferIndex(this.Count);
            T result = buffer[endIndex];
            buffer[endIndex] = default(T);

            return result;
        }

        public void AddRange(IEnumerable<T> collection)
        {
            AddLastRange(collection);
        }

        public void AddFirstRange(IEnumerable<T> collection)
        {
            AddFirstRange(collection, 0, DequeUtility.Count(collection));
        }

        public void AddFirstRange(
            IEnumerable<T> collection,
            int fromIndex,
            int count)
        {
            InsertRange(0, collection, fromIndex, count);
        }

        public void AddLastRange(IEnumerable<T> collection)
        {
            AddLastRange(collection, 0, DequeUtility.Count(collection));
        }

        public void AddLastRange(
            IEnumerable<T> collection,
            int fromIndex,
            int count)
        {
            InsertRange(this.Count, collection, fromIndex, count);
        }

        public void InsertRange(int index, IEnumerable<T> collection)
        {
            int count = DequeUtility.Count(collection);
            this.InsertRange(index, collection, 0, count);
        }

        public void InsertRange(
            int index,
            IEnumerable<T> collection,
            int fromIndex,
            int count)
        {
            checkIndexOutOfRange(index - 1);

            if (0 == count)
            {
                return;
            }

            ensureCapacityFor(count);

            if (index < this.Count / 2)
            {
                if (index > 0)
                {
                    int copyCount = index;
                    int shiftIndex = this.Capacity - count;
                    for (int j = 0; j < copyCount; j++)
                    {
                        buffer[toBufferIndex(shiftIndex + j)] =
                            buffer[toBufferIndex(j)];
                    }
                }

                this.shiftStartOffset(-count);

            }
            else
            {
                if (index < this.Count)
                {
                    int copyCount = this.Count - index;
                    int shiftIndex = index + count;
                    for (int j = 0; j < copyCount; j++)
                    {
                        buffer[toBufferIndex(shiftIndex + j)] =
                            buffer[toBufferIndex(index + j)];
                    }
                }
            }

            int i = index;
            foreach (T item in collection)
            {
                buffer[toBufferIndex(i)] = item;
                ++i;
            }

            incrementCount(count);
        }

        public void RemoveRange(int index, int count)
        {
            if (this.IsEmpty)
            {
                throw new InvalidOperationException("The Deque is empty");
            }
            if (index > Count - count)
            {
                throw new IndexOutOfRangeException(
                    "The supplied index is greater than the Count");
            }

            ClearBuffer(index, count);

            if (index == 0)
            {
                this.shiftStartOffset(count);
                this.Count -= count;
                return;
            }
            else if (index == Count - count)
            {
                this.Count -= count;
                return;
            }

            if ((index + (count / 2)) < Count / 2)
            {
                int copyCount = index;
                int writeIndex = count;
                for (int j = 0; j < copyCount; j++)
                {
                    buffer[toBufferIndex(writeIndex + j)]
                        = buffer[toBufferIndex(j)];
                }

                this.shiftStartOffset(count);
            }
            else
            {
                int copyCount = Count - count - index;
                int readIndex = index + count;
                for (int j = 0; j < copyCount; ++j)
                {
                    buffer[toBufferIndex(index + j)] =
                        buffer[toBufferIndex(readIndex + j)];
                }
            }

            decrementCount(count);
        }
        public T Get(int index)
        {
            checkIndexOutOfRange(index);
            return buffer[toBufferIndex(index)];
        }

        public void Set(int index, T item)
        {
            checkIndexOutOfRange(index);
            buffer[toBufferIndex(index)] = item;
        }

    }
}


use std::io::{self, prelude::*};
use std::str;

struct Scanner<R> {
    reader: R,
    buf_str: Vec<u8>,
    buf_iter: str::SplitWhitespace<'static>,
}
impl<R: BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        Self { reader, buf_str: vec![], buf_iter: "".split_whitespace() }
    }
    fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buf_iter.next() {
                return token.parse().ok().expect("Failed parse");
            }
            self.buf_str.clear();
            self.reader.read_until(b'\n', &mut self.buf_str).expect("Failed read");
            self.buf_iter = unsafe {
                let slice = str::from_utf8_unchecked(&self.buf_str);
                std::mem::transmute(slice.split_whitespace())
            }
        }
    }
}

fn solve<R: BufRead, W: Write>(scan: &mut Scanner<R>, w: &mut W) {
    let t = scan.token::<usize>();
    for _ in 0..t {
        let mut n = scan.token::<i32>();

        let mut cnt = 0;
        let div2 = loop {
            if n % 2 != 0 {
                break cnt;
            }
            n /= 2;
            cnt += 1;
        };
        cnt = 0;
        let div3 = loop {
            if n % 3 != 0 {
                break cnt;
            }
            n /= 3;
            cnt += 1;
        };

        let ans = if n > 1 || div2 > div3 { -1 } else { 2 * div3 - div2 };

        writeln!(w, "{}", ans).ok();
    }
}

fn main() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = Scanner::new(stdin.lock());
    let mut out = io::BufWriter::new(stdout.lock());
    solve(&mut scan, &mut out);
}


use std::fmt::Debug;
use std::str::FromStr;

pub struct TokenReader {
    reader: std::io::Stdin,
    tokens: Vec<String>,
    index: usize,
}

impl TokenReader {
    pub fn new() -> Self {
        Self {
            reader: std::io::stdin(),
            tokens: Vec::new(),
            index: 0,
        }
    }

    pub fn next<T>(&mut self) -> T
    where
        T: FromStr,
        T::Err: Debug,
    {
        if self.index >= self.tokens.len() {
            self.load_next_line();
        }
        self.index += 1;
        self.tokens[self.index - 1].parse().unwrap()
    }

    pub fn vector<T>(&mut self) -> Vec<T>
    where
        T: FromStr,
        T::Err: Debug,
    {
        if self.index >= self.tokens.len() {
            self.load_next_line();
        }
        self.index = self.tokens.len();
        self.tokens.iter().map(|tok| tok.parse().unwrap()).collect()
    }

    pub fn load_next_line(&mut self) {
        let mut line = String::new();
        self.reader.read_line(&mut line).unwrap();

        self.tokens = line
            .split_whitespace()
            .map(String::from)
            .collect();
        self.index = 0;
    }
}

fn solve(mut n: i32) -> i32 {
    let mut twos = 0;
    while n % 2 == 0 {
        n /= 2;
        twos += 1;
    }

    let mut threes = 0;
    while n % 3 == 0 {
        n /= 3;
        threes += 1;
    }

    if n != 1 || twos > threes {
        return -1;
    }

    2 * threes - twos
}

fn main() {
    let mut reader = TokenReader::new();
    let tests = reader.next::<usize>();

    for _ in 0..tests {
        let n = reader.next::<i32>();
        let res = solve(n);
        println!("{}", res);
    }
}


use std::io;

fn main() -> io::Result<()> {
    let mut input = String::new();

    io::stdin().read_line(&mut input)?;
    let n = input.trim().parse().unwrap();
    for _ in 0..n {
        input.clear();
        io::stdin().read_line(&mut input)?;

        let n =  input.trim().parse::<i64>().unwrap();
        let result = solve(n);

        println!("{}", result);

    }

    return Ok(());
}

fn solve(mut n: i64) -> String {
    let mut steps = 0;
    while n != 1 {
        if n % 6 == 0 {
            n /= 6;
        } else if n % 3 == 0 {
            n *= 2;
        } else {
            return (-1).to_string();
        }
        steps += 1;
    }

    return steps.to_string();
}


#![allow(dead_code)]
#![allow(unused_imports)]

use std::cmp::*;
use std::collections::*;
use std::io;
use std::ops;
use std::str::FromStr;

#[derive(Clone, Debug, Default)]
struct ProblemState {
}

impl Problem {
    fn solve(&mut self) {
        let mut n: u64 = self.scan();

        let mut k2 = 0u64;
        let mut k3 = 0u64;

        while n % 2 == 0 {
            k2 += 1;
            n /= 2;
        }

        while n % 3 == 0 {
            k3 += 1;
            n /= 3;
        }

        if n == 1 && k3 >= k2 {
            println!("{}", 2 * k3 - k2);
        } else {
            println!("-1");
        }
    }
}

fn main() {
    Problem::new().solve_cases();
}

struct Problem {
    input_state: InputState,
    problem_state: ProblemState,
}

struct InputState {
    stdin: io::Stdin,
    buffer: String,
    tokens: VecDeque<String>,
}

impl Problem {
    fn new() -> Self {
        Self {
            input_state: InputState {
                stdin: io::stdin(),
                buffer: String::new(),
                tokens: VecDeque::new(),
            },
            problem_state: Default::default(),
        }
    }

    fn solve_cases(&mut self) {
        for _ in 0usize..self.scan() {
            self.solve()
        }
    }

    fn scan<T: FromStr>(&mut self) -> T {
        while self.input_state.tokens.is_empty() {
            self.input_state.stdin.read_line(&mut self.input_state.buffer).unwrap();

            for token in self.input_state.buffer.split_ascii_whitespace() {
                self.input_state.tokens.push_back(token.to_string());
            }

            self.input_state.buffer.clear();
        }

        self.input_state.tokens.pop_front().unwrap().parse().ok().unwrap()
    }

    fn scan_vec<T: FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).into_iter().map(|_| self.scan()).collect()
    }

    fn scan_line(&mut self) -> String {
        let mut line = String::new();
        self.input_state.stdin.read_line(&mut line).unwrap();
        while line.ends_with('\n') || line.ends_with('\r') { line.pop(); }
        line
    }

    fn scan_line_vec(&mut self, n: usize) -> Vec<String> {
        (0..n).into_iter().map(|_| self.scan_line()).collect()
    }
}

impl ops::Deref for Problem {
    type Target = ProblemState;

    fn deref(&self) -> &ProblemState {
        &self.problem_state
    }
}

impl ops::DerefMut for Problem {
    fn deref_mut(&mut self) -> &mut ProblemState {
        &mut self.problem_state
    }
}


//spnauti-rusT {{{
use std::io::*; use std::str::{self,*}; use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_imports)] use std::cell::*;
#[allow(unused_macros)] macro_rules! m {
	($c:tt,$x:expr,$y:expr) => {{
		let b=$y; let a=&mut$x; if b$c*a {*a=b; true} else {false}
	}};
}
#[allow(unused_macros)] macro_rules! l {
	($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};
	($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};
	(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};
	(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};
}
#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }
#[allow(unused_macros)] fn reader() -> WordReaderC { WordReaderC::new() }
#[allow(unused_macros)] fn writer() -> BufWriter<Stdout> { BufWriter::new(stdout()) }
struct WordReaderC {buf: Vec<u8>, pos: usize, q: std::io::StdinLock<'static>}//'
#[allow(dead_code)] impl WordReaderC {
	fn new() -> Self {
		let r = unsafe {&*Box::into_raw(Box::new(stdin()))};
		Self { q: r.lock(), buf: Vec::new(), pos: 0 }
	}
	fn next_line(&mut self) -> bool {
		self.buf.clear(); self.pos = 0;
		self.q.read_until(b'\n', &mut self.buf).unwrap_or(0) > 0
	}
	fn is_ws(c: u8) -> bool {
		c == b' ' || c == b'\r' || c == b'\n' || c == b'\t'
	}
	fn byte(&mut self) -> Option<u8> {
		if self.pos == self.buf.len() { if !self.next_line() { return None; } }
		self.pos += 1; Some(self.buf[self.pos - 1])
	}
	fn vb(&mut self) -> Vec<u8> {
		let mut s = Vec::with_capacity(8);
		let mut f = false;
		loop {
			if let Some(c) = self.byte() {
				if !Self::is_ws(c) {
					s.push(c);
					f = true;
				} else if f { break; }
			} else { break; }
		}
		s
	}
	fn s(&mut self) -> String { String::from_utf8(self.vb()).expect("invalid utf8") }
	fn i(&mut self) ->    i32 { self.p() }
	fn l(&mut self) ->    i64 { self.p() }
	fn u(&mut self) ->  usize { self.p() }
	fn f(&mut self) ->    f64 { self.p() }
	fn vi(&mut self, n: usize) -> Vec<i32> { self.vp(n) }
	fn vl(&mut self, n: usize) -> Vec<i64> { self.vp(n) }
	fn vu(&mut self, n: usize) -> Vec<usize> { self.vp(n) }
	fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> { self.ip(n).into_iter() }
	fn iu(&mut self, n: usize) -> impl Iterator<Item=usize> { self.ip(n).into_iter() }
	fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
		let w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::<T>().unwrap()
	}
	fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
		(0..n).map(|_|self.p()).collect()
	}
	fn ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
		self.vp(n).into_iter()
	}
}
//------------------- End rusT }}}

fn main() {
	let mut rin = reader();
	let mut rout = writer();

	rep!{[rin.u()]
		let f = |mut n:i32, a:i32| -> (i32,i32) {
			let mut res = 0;
			while n % a == 0 {
				n /= a;
				res += 1;
			}
			(n, res)
		};
		let n = rin.i();
		let (n,a2) = f(n,2);
		let (n,a3) = f(n,3);
		let sol = if n > 1 || a2 > a3 {-1} else {2 * a3 - a2};
		writeln!(rout, "{}", sol).ok();
	};
}


#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(dead_code)]

#[allow(unused_macros)]
macro_rules! invec {
    ( $ t : ty ) => {{
        let mut s = String::new();
        match std::io::stdin().read_line(&mut s) {
            Ok(0) => Vec::<$t>::new(),
            Ok(n) => s
                .trim()
                .split_whitespace()
                .map(|s| s.parse::<$t>().unwrap())
                .collect::<Vec<$t>>(),
            Err(_) => Vec::<$t>::new(),
        }
    }};
}

#[allow(unused_macros)]
macro_rules! get {
      ($t:ty) => {
          {
              let mut line: String = String::new();
              std::io::stdin().read_line(&mut line).unwrap();
              line.trim().parse::<$t>().unwrap()
          }
      };
      ($($t:ty),*) => {
          {
              let mut line: String = String::new();
              std::io::stdin().read_line(&mut line).unwrap();
              let mut iter = line.split_whitespace();
              (
                  $(iter.next().unwrap().parse::<$t>().unwrap(),)*
              )
          }
      };
      ($t:ty; $n:expr) => {
          (0..$n).map(|_|
              get!($t)
          ).collect::<Vec<_>>()
      };
      ($($t:ty),*; $n:expr) => {
          (0..$n).map(|_|
              get!($($t),*)
          ).collect::<Vec<_>>()
      };
      ($t:ty ;;) => {
          {
              let mut line: String = String::new();
              std::io::stdin().read_line(&mut line).unwrap();
              line.split_whitespace()
                  .map(|t| t.parse::<$t>().unwrap())
                  .collect::<Vec<_>>()
          }
      };
      ($t:ty ;; $n:expr) => {
          (0..$n).map(|_| get!($t ;;)).collect::<Vec<_>>()
      };
}

#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
    ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($next:expr, [$t:tt]) => {
        {
            let len = read_value!($next, usize);
            (0..len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
        }
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
#[cfg(debug_assertions)]
macro_rules! mydbg {
    //($arg:expr) => (dbg!($arg))
    //($arg:expr) => (println!("{:?}",$arg));
      ($($a:expr),*) => {
          eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
      }
}
#[cfg(not(debug_assertions))]
macro_rules! mydbg {
    ($($arg:expr),*) => {};
}

macro_rules! echo {
    ($($a:expr),*) => {
          $(println!("{}",$a))*
      }
}

use std::cmp::*;
use std::collections::*;
use std::ops::{Add, Div, Mul, Sub};

#[allow(dead_code)]
static INF_I64: i64 = i64::max_value() / 2;
#[allow(dead_code)]
static INF_I32: i32 = i32::max_value() / 2;
#[allow(dead_code)]
static INF_USIZE: usize = usize::max_value() / 2;
#[allow(dead_code)]
static M_O_D: usize = 1000000007;
#[allow(dead_code)]
static PAI: f64 = 3.1415926535897932;

trait IteratorExt: Iterator {
    fn toVec(self) -> Vec<Self::Item>;
}

impl<T: Iterator> IteratorExt for T {
    fn toVec(self) -> Vec<Self::Item> {
        self.collect()
    }
}

trait CharExt {
    fn toNum(&self) -> usize;
    fn toAlphabetIndex(&self) -> usize;
    fn toNumIndex(&self) -> usize;
}
impl CharExt for char {
    fn toNum(&self) -> usize {
        return *self as usize;
    }
    fn toAlphabetIndex(&self) -> usize {
        return self.toNum() - 'a' as usize;
    }
    fn toNumIndex(&self) -> usize {
        return self.toNum() - '0' as usize;
    }
}

trait VectorExt {
    fn joinToString(&self, s: &str) -> String;
}
impl<T: ToString> VectorExt for Vec<T> {
    fn joinToString(&self, s: &str) -> String {
        return self
            .iter()
            .map(|x| x.to_string())
            .collect::<Vec<_>>()
            .join(s);
    }
}

trait StringExt {
    fn get_reverse(&self) -> String;
}
impl StringExt for String {
    fn get_reverse(&self) -> String {
        self.chars().rev().collect::<String>()
    }
}

trait UsizeExt {
    fn pow(&self, n: usize) -> usize;
}
impl UsizeExt for usize {
    fn pow(&self, n: usize) -> usize {
        return ((*self as u64).pow(n as u32)) as usize;
    }
}

fn main() {
    let T = get!(usize);
    for testcase in 0..T {
        let mut ans: usize = 0;
        let n = get!(u64);

        let mut a = n;
        let mut flag = true;
        while true {
            if a == 1 {
                break;
            }
            if a > n * 2 {
                flag = false;
                break;
            }
            if a % 6 == 0 {
                a /= 6;
                ans += 1;
            } else {
                a *= 2;
                ans += 1;
            }
        }
        echo!(if flag {
            ans.to_string()
        } else {
            "-1".to_string()
        });
    }
}


#![allow(unused_imports)]
#![allow(dead_code)]

use std::io::Read;

struct State {
    n: usize
}

fn solve(st: &mut State) {
    let mut n = st.n;
    let mut c2 = 0;
    let mut c3 = 0;
    while n % 2 == 0 {
        c2 += 1;
        n /= 2;
    }
    while n % 3 == 0 {
        c3 += 1;
        n /= 3;
    }
    if n > 1 || c2 > c3 {
        print!("-1\n");
        return;
    }
    print!("{}\n", c3 - c2 + c3);
}
fn main() {
    let mut buffer = String::new();
    std::io::stdin().read_to_string(&mut buffer).unwrap();
    let mut input = buffer.split_whitespace();

    let t: usize = input.next().unwrap().parse().unwrap();
    for _ in 0..t {
        let n: usize = input.next().unwrap().parse().unwrap();
        //let s: Vec<char> = input.next().unwrap().chars().collect();
        //let a: Vec<i32> = (0..m).map(|_| input.next().unwrap().parse().unwrap()).collect();
        solve(&mut State{n: n});
    }

}


use std::io::{self, BufRead};

fn main() {
  let stdin = io::stdin();

  for t in stdin.lock().lines().skip(1) {
    let mut n = t.unwrap().parse::<u64>().unwrap();
    let mut s = 0;

    while n % 6 == 0 {
      n /= 6;
      s += 1;
    }

    while n % 3 == 0 {
      n /= 3;
      s += 2;
    }

    println!("{}", if n == 1 { s } else { -1 });
  }
}


use std::io::Read;
fn main() {
    let stdin = std::io::stdin();
    let mut stdin = stdin.lock();
    let mut next_int = || {
        let n: i64 = stdin
            .by_ref()
            .bytes()
            .map(|b| b.unwrap() as char)
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect::<String>()
            .parse()
            .unwrap();
        n
    };
    let n = next_int();
    for _ in 0..n {
        let mut n = next_int();
        let mut a = 0;
        let mut b = 0;
        let flag = loop {
            if n == 1 {
                break true;
            }
            if n % 2 == 0 {
                n /= 2;
                a += 1;
                continue;
            }
            if n % 3 == 0 {
                n /= 3;
                b += 1;
                continue;
            }
            break false;
        };

        let ans = if !flag {
            -1
        } else {
            if a > b {
                -1
            } else {
                b - a + b
            }
        };
        println!("{}", ans);
    }
}


use std::io::{self, Read};

struct Case {
    n: u32,
}

impl Case {
    pub fn parse(line: &str) -> Option<Case> {
        assert!(!line.contains(|ch: char| ch == '\r' || ch == '\n'));

        let n = u32::from_str_radix(line, 10).ok()?;

        Some(Case {
            n,
        })
    }

    pub fn solution(&self) -> Option<u32> {
        let mut n = self.n;
        let mut counter = 0;

        loop {
            if n == 1 {
                return Some(counter);
            } else if n % 3 != 0 {
                return None;
            } else if n % 6 != 0 {
                n = 2 * n;
            } else {
                n = n / 6;
            }

            counter += 1;
        }
    }
}

fn main() -> io::Result<()> {
    let input = io::stdin();
    let mut line = String::new();
    input.read_line(&mut line)?;
    let t = u32::from_str_radix(line.trim(), 10).expect("Invalid value for t");

    for _ in 0..t {
        line.clear();
        input.read_line(&mut line)?;
        let case = Case::parse(line.trim()).expect("Failed to parse case");
        match case.solution() {
            Some(sol) => println!("{}", sol),
            None => println!("-1"),
        }
    }

    Ok(())
}


//  ____            _                  _                       _       _
// |  _ \ _   _ ___| |_    ___ _ __   | |_ ___ _ __ ___  _ __ | | __ _| |_ ___
// | |_) | | | / __| __|  / __| '_ \  | __/ _ \ '_ ` _ \| '_ \| |/ _` | __/ _ \
// |  _ <| |_| \__ \ |_  | (__| |_) | | ||  __/ | | | | | |_) | | (_| | ||  __/
// |_| \_\\__,_|___/\__|  \___| .__/___\__\___|_| |_| |_| .__/|_|\__,_|\__\___|
//                            |_| |_____|               |_|

//https://github.com/manta1130/Competitive_Programming_Template_Rust

#[macro_use]
mod input {

    use std;
    use std::io;

    const SPLIT_DELIMITER: char = ' ';

    #[macro_export]
    #[allow(unused_macros)]
    macro_rules! input {
    ( $($x:expr ),*) => {
        {
            let temp_str = input_line_str();
            let mut split_result_iter = temp_str.split_whitespace();
                $(
                let buf_split_result = split_result_iter.next();
                let buf_split_result = buf_split_result.unwrap();
                    ($x) = buf_split_result.parse().unwrap();
                )*
        }
    };
}

    #[allow(dead_code)]
    pub fn input_line_str() -> String {
        let mut s = String::new();
        io::stdin().read_line(&mut s).unwrap();
        s.trim().to_string()
    }

    #[allow(dead_code)]
    pub fn p<T>(t: T)
    where
        T: std::fmt::Display,
    {
        println!("{}", t);
    }

    #[allow(dead_code)]
    pub fn input_vector2d<T>(line: usize) -> Vec<Vec<T>>
    where
        T: std::str::FromStr,
    {
        let mut v: Vec<Vec<T>> = Vec::new();

        for _ in 0..line {
            let vec_line = input_vector();
            v.push(vec_line);
        }
        v
    }

    #[allow(dead_code)]
    pub fn input_vector<T>() -> Vec<T>
    where
        T: std::str::FromStr,
    {
        let mut v: Vec<T> = Vec::new();

        let s = input_line_str();
        let split_result = s.split(SPLIT_DELIMITER);
        for z in split_result {
            let buf = match z.parse() {
                Ok(r) => r,
                Err(_) => panic!("Parse Error"),
            };
            v.push(buf);
        }
        v
    }

    #[allow(dead_code)]
    pub fn input_vector_row<T>(n: usize) -> Vec<T>
    where
        T: std::str::FromStr,
    {
        let mut v = Vec::with_capacity(n);
        for _ in 0..n {
            let buf = match input_line_str().parse() {
                Ok(r) => r,
                Err(_) => panic!("Parse Error"),
            };
            v.push(buf);
        }
        v
    }

    pub trait ToCharVec {
        fn to_charvec(&self) -> Vec<char>;
    }

    impl ToCharVec for String {
        fn to_charvec(&self) -> Vec<char> {
            self.to_string().chars().collect::<Vec<_>>()
        }
    }
}

#[allow(unused_imports)]
use input::*;
#[allow(unused_imports)]
use std::io::{stdout, BufWriter, Write};
fn main() {
    let out = stdout();
    let mut out = BufWriter::new(out.lock());

    let n: usize;
    input!(n);
    for _ in 0..n {
        let mut x: usize;
        input!(x);
        let mut count = 0;
        while x > 1 && x % 6 == 0 {
            x /= 6;
            count += 1;
        }
        while x > 1 && x % 3 == 0 {
            x /= 3;
            count += 2;
        }
        if x != 1 {
            writeln!(out,"-1").unwrap();
        } else {
            writeln!(out,"{}", count).unwrap();
        }
    }
}


//  ____            _                  _                       _       _
// |  _ \ _   _ ___| |_    ___ _ __   | |_ ___ _ __ ___  _ __ | | __ _| |_ ___
// | |_) | | | / __| __|  / __| '_ \  | __/ _ \ '_ ` _ \| '_ \| |/ _` | __/ _ \
// |  _ <| |_| \__ \ |_  | (__| |_) | | ||  __/ | | | | | |_) | | (_| | ||  __/
// |_| \_\\__,_|___/\__|  \___| .__/___\__\___|_| |_| |_| .__/|_|\__,_|\__\___|
//                            |_| |_____|               |_|

//https://github.com/manta1130/Competitive_Programming_Template_Rust

#[macro_use]
mod input {

    use std;
    use std::io;

    const SPLIT_DELIMITER: char = ' ';

    #[macro_export]
    #[allow(unused_macros)]
    macro_rules! input {
    ( $($x:expr ),*) => {
        {
            let temp_str = input_line_str();
            let mut split_result_iter = temp_str.split_whitespace();
                $(
                let buf_split_result = split_result_iter.next();
                let buf_split_result = buf_split_result.unwrap();
                    ($x) = buf_split_result.parse().unwrap();
                )*
        }
    };
}

    #[allow(dead_code)]
    pub fn input_line_str() -> String {
        let mut s = String::new();
        io::stdin().read_line(&mut s).unwrap();
        s.trim().to_string()
    }

    #[allow(dead_code)]
    pub fn p<T>(t: T)
    where
        T: std::fmt::Display,
    {
        println!("{}", t);
    }

    #[allow(dead_code)]
    pub fn input_vector2d<T>(line: usize) -> Vec<Vec<T>>
    where
        T: std::str::FromStr,
    {
        let mut v: Vec<Vec<T>> = Vec::new();

        for _ in 0..line {
            let vec_line = input_vector();
            v.push(vec_line);
        }
        v
    }

    #[allow(dead_code)]
    pub fn input_vector<T>() -> Vec<T>
    where
        T: std::str::FromStr,
    {
        let mut v: Vec<T> = Vec::new();

        let s = input_line_str();
        let split_result = s.split(SPLIT_DELIMITER);
        for z in split_result {
            let buf = match z.parse() {
                Ok(r) => r,
                Err(_) => panic!("Parse Error"),
            };
            v.push(buf);
        }
        v
    }

    #[allow(dead_code)]
    pub fn input_vector_row<T>(n: usize) -> Vec<T>
    where
        T: std::str::FromStr,
    {
        let mut v = Vec::with_capacity(n);
        for _ in 0..n {
            let buf = match input_line_str().parse() {
                Ok(r) => r,
                Err(_) => panic!("Parse Error"),
            };
            v.push(buf);
        }
        v
    }

    pub trait ToCharVec {
        fn to_charvec(&self) -> Vec<char>;
    }

    impl ToCharVec for String {
        fn to_charvec(&self) -> Vec<char> {
            self.to_string().chars().collect::<Vec<_>>()
        }
    }
}

#[allow(unused_imports)]
use input::*;
#[allow(unused_imports)]
use std::io::{stdout, BufWriter, Write};
fn main() {
    let out = stdout();
    let mut out = BufWriter::new(out.lock());

    let n: usize;
    input!(n);
    for _ in 0..n {
        let mut x: usize;
        input!(x);
        let mut count = 0;
        while x > 1 && x % 6 == 0 {
            x /= 6;
            count += 1;
        }
        while x > 1 && x % 3 == 0 {
            x /= 3;
            count += 2;
        }
        if x != 1 {
            println!("-1");
        } else {
            println!("{}", count);
        }
    }
}


use std::io::{stdin, BufWriter, Write, stdout};

#[allow(dead_code)]
fn parse_i32(line: &mut String) -> i32 {
	line.clear();
	stdin().read_line(line).unwrap();
	line.trim().parse::<i32>().unwrap()
}

#[allow(dead_code)]
fn parse_i32s(line: &mut String, output: &mut Vec<i32>) {
	line.clear();
	stdin().read_line(line).unwrap();
	output.clear();
	for x in line.trim().split(' ').map(|x| x.parse::<i32>().unwrap()) {
		output.push(x);
	}
}

fn main() {
	let mut out = BufWriter::new(stdout());
	let mut line = String::new();
	let t = parse_i32(&mut line);
	for _ in 0..t {
		let mut n = parse_i32(&mut line);
		let mut twos = 0;
		let mut threes = 0;
		while n % 2 == 0 {
			twos += 1;
			n /= 2;
		}
		while n % 3 == 0 {
			threes += 1;
			n /= 3;
		}
		if n != 1 || twos > threes {
			writeln!(out, "-1").ok();
			continue;
		}
		writeln!(out, "{}", threes + (threes - twos)).ok();
	}
}


use std::io::{self, BufRead};

fn main() {
  let stdin = io::stdin();
  let mut lines = stdin.lock().lines();
  let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
  for _ in 0..t {
    let mut n: usize = lines.next().unwrap().unwrap().parse().unwrap();
    let mut n2: usize = 0;
    let mut n3: usize = 0;
    while n % 2 == 0 {
      n2 += 1;
      n /= 2;
    }
    while n % 3 == 0 {
      n3 += 1;
      n /= 3;
    }
    if n > 1 {
      println!("-1");
    } else if n2 > n3 {
      println!("-1");
    } else {
      println!("{}", 2 * n3 - n2);
    }
  }
}


// Author: Param Singh <paramsingh258@gmail.com>
// Kefa and Park: http://codeforces.com/contest/580/problem/C

import java.io.*;
import java.util.*;
public class Kefa {
    static class Node {
        List<Node> children;
        int id;
        int num;
        boolean cat;
        int left, right;
        Node() {
            left = right = 0;
            children = new ArrayList<Node>();
            num = 0;
            cat = false;
        }

        void add_child(Node x) {
            num++;
            children.add(x);
        }

        void add_cat() {
            cat = true;
        }
    }

    public static int num_leafs(Node vertex, Node prev, int consecutive, int m) {
        if (vertex.num == 1) {
            if (vertex.cat)
                consecutive++;
            if (m >= consecutive)
                return 1;
            else
                return 0;
        }
        else {
            int ans = 0;
            if (vertex.cat) {
                if (m == consecutive)
                    return 0;
                else {
                    for (Node x: vertex.children) {
                        if (prev != null && prev.id == x.id)
                            continue;
                        ans += num_leafs(x, vertex, consecutive+1, m);
                    }
                    return ans;
                }
            }
            else {
                for (Node x: vertex.children) {
                    if (prev != null && prev.id == x.id)
                        continue;
                    ans += num_leafs(x, vertex, 0, m);
                }
                return ans;
            }
        }
    }

    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String s[] = in.readLine().split(" ");
        int n = Integer.parseInt(s[0]);
        int m = Integer.parseInt(s[1]);

        s = in.readLine().split(" ");
        Node tree[] = new Node[n];

        for (int i = 0; i < n; i++) {
            tree[i] = new Node();
            tree[i].id = i;
            if (s[i].equals("1"))
                tree[i].add_cat();
        }

        if (n == 1) {
            if (tree[0].cat && m != 0)
                System.out.println(0);
            else
                System.out.println(1);
            System.exit(0);
        }

        int a, b;
        for (int i = 1; i < n; i++) {
            s = in.readLine().split(" ");
            a = Integer.parseInt(s[0]);
            b = Integer.parseInt(s[1]);
            tree[a-1].add_child(tree[b-1]);
            tree[b-1].add_child(tree[a-1]);
        }
        System.out.println(num_leafs(tree[0], null, 0, m));
    }
}


// Author: Param Singh <paramsingh258@gmail.com>
// Kefa and Park: http://codeforces.com/contest/580/problem/C

import java.io.*;
import java.util.*;
public class Kefa {
    static class Node {
        List<Node> children;
        int id;
        int num;
        boolean cat;
        int left, right;
        Node() {
            left = right = 0;
            children = new ArrayList<Node>();
            num = 0;
            cat = false;
        }

        void add_child(Node x) {
            num++;
            children.add(x);
        }

        void add_cat() {
            cat = true;
        }
    }

    public static int num_leafs(Node vertex, Node prev, int consecutive, int m) {
        int ans = 0;
        if (vertex.num == 1 && prev != null) {
            if (vertex.cat)
                consecutive++;
            if (m >= consecutive)
                ans = 1;
            else
                ans = 0;
        }
        else {
            if (vertex.cat) {
                if (m == consecutive)
                    ans = 0;
                else {
                    for (Node x: vertex.children) {
                        if (prev != null && prev.id == x.id)
                            continue;
                        ans += num_leafs(x, vertex, consecutive+1, m);
                    }
                }
            }
            else {
                for (Node x: vertex.children) {
                    if (prev != null && prev.id == x.id)
                        continue;
                    ans += num_leafs(x, vertex, 0, m);
                }
                return ans;
            }
        }
        return ans;
    }

    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String s[] = in.readLine().split(" ");
        int n = Integer.parseInt(s[0]);
        int m = Integer.parseInt(s[1]);

        s = in.readLine().split(" ");
        Node tree[] = new Node[n];

        for (int i = 0; i < n; i++) {
            tree[i] = new Node();
            tree[i].id = i;
            if (s[i].equals("1"))
                tree[i].add_cat();
        }

        if (n == 1) {
            if (tree[0].cat && m != 0)
                System.out.println(0);
            else
                System.out.println(1);
            System.exit(0);
        }

        int a, b;
        for (int i = 1; i < n; i++) {
            s = in.readLine().split(" ");
            a = Integer.parseInt(s[0]);
            b = Integer.parseInt(s[1]);
            tree[a-1].add_child(tree[b-1]);
            tree[b-1].add_child(tree[a-1]);
        }
        System.out.println(num_leafs(tree[0], null, 0, m));
    }
}


import java.util.*;
public class Test {
	public static void main(String args[]){
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		int m=sc.nextInt();
		vertex[] v=new vertex[n];
		for(int i=0;i<n;i++){
			v[i]=new vertex(i,sc.nextInt());
		}
		for(int i=0;i<n-1;i++){
			int a=sc.nextInt()-1;
			int b=sc.nextInt()-1;
			v[a].next.add(v[a].n, v[b]);
			v[a].n++;
			v[b].next.add(v[b].n,v[a]);
			v[b].n++;
		}
		Stack<vertex> st=new Stack<vertex>();
		st.push(v[0]);
		int[] visited=new int[n];
		if(v[0].cat) v[0].c++;
		visited[0]=1;
		int cnt=0;
		while(!st.isEmpty()){
			vertex tmp=st.pop();
			int flag=0;
			for(int i=0;i<tmp.n;i++){
				if(visited[tmp.next.get(i).id]==0){
					flag=1;
					if(tmp.c<=m){
						st.push(tmp.next.get(i));
					}
						visited[tmp.next.get(i).id]=1;

					if(tmp.next.get(i).cat||tmp.c>m){
						tmp.next.get(i).c=1+tmp.c;
					}
				}
			}
			if(flag==0&&tmp.c<=m){
				cnt++;
			}
		}
		System.out.println(cnt);
	}
}
class vertex{
	boolean cat;
	int n;
	int c=0;
	ArrayList<vertex> next=new ArrayList<vertex>();
	int id;
	vertex(int i,int a){
		if(a==1) cat=true;
		else cat=false;
		id=i;
	}
}


import java.util.*;
public class Test {
	public static void main(String args[]){
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		int m=sc.nextInt();
		vertex[] v=new vertex[n];
		for(int i=0;i<n;i++){
			v[i]=new vertex(i,sc.nextInt());
		}
		for(int i=0;i<n-1;i++){
			int a=sc.nextInt()-1;
			int b=sc.nextInt()-1;
			v[a].n++;
			v[b].n++;
			v[a].next.add(v[b]);
			v[b].next.add(v[a]);
		}
		Stack<vertex> st=new Stack<vertex>();
		st.push(v[0]);
		int[] visited=new int[n];
		if(v[0].cat) v[0].c++;
		visited[0]=1;
		int cnt=0;
		while(!st.isEmpty()){
			vertex tmp=st.pop();
			int flag=0;
			for(int i=0;i<tmp.n;i++){
				if(visited[tmp.next.get(i).id]==0){
					flag=1;
					st.push(tmp.next.get(i));
					visited[tmp.next.get(i).id]=1;
					if(tmp.next.get(i).cat||tmp.c>m){
						tmp.next.get(i).c=1+tmp.c;
					}
				}
			}
			if(flag==0&&tmp.c<=m){
				cnt++;
			}
		}
		System.out.println(cnt);
	}
}
class vertex{
	boolean cat;
	int n;
	int c=0;
	LinkedList<vertex> next=new LinkedList<vertex>();
	int id;
	vertex(int i,int a){
		if(a==1) cat=true;
		else cat=false;
		id=i;
	}
}


import java.util.*;
public class Test {
	public static void main(String args[]){
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		int m=sc.nextInt();
		vertex[] v=new vertex[n];
		for(int i=0;i<n;i++){
			v[i]=new vertex(i,sc.nextInt());
		}
		for(int i=0;i<n-1;i++){
			int a=sc.nextInt()-1;
			int b=sc.nextInt()-1;
			v[a].n++;
			v[b].n++;
			v[a].next.add(v[b]);
			v[b].next.add(v[a]);
		}
		Stack<vertex> st=new Stack<vertex>();
		st.push(v[0]);
		int[] visited=new int[n];
		if(v[0].cat) v[0].c++;
		visited[0]=1;
		int cnt=0;
		while(!st.isEmpty()){
			vertex tmp=st.pop();
			int flag=0;
			for(int i=0;i<tmp.n;i++){
				if(visited[tmp.next.get(i).id]==0){
					flag=1;
					if(tmp.c<=m){
						st.push(tmp.next.get(i));
					}
						visited[tmp.next.get(i).id]=1;

					if(tmp.next.get(i).cat||tmp.c>m){
						tmp.next.get(i).c=1+tmp.c;
					}
				}
			}
			if(flag==0&&tmp.c<=m){
				cnt++;
			}
		}
		System.out.println(cnt);
	}
}
class vertex{
	boolean cat;
	int n;
	int c=0;
	LinkedList<vertex> next=new LinkedList<vertex>();
	int id;
	vertex(int i,int a){
		if(a==1) cat=true;
		else cat=false;
		id=i;
	}
}


import java.lang.*;
import java.io.*;
import java.util.*;

public class Park {

	public static void main(String[] args) throws java.lang.Exception {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskA solver = new TaskA();
		solver.solve(in, out);
		out.close();
	}
}

class TaskA {
	public final static int maxn = (int)(1e5+5);
	public adj[] E = new adj[maxn];
	public int[] a = new int[maxn];
	int n, m;
	int ans = 0;

	public void solve(InputReader in, PrintWriter out) {
		n = in.nextInt();
		m = in.nextInt();
		int i, j, k;

		for (i=1; i<=n; ++i) {
			a[i] = in.nextInt();
			E[i] = new adj();
		}

		for (i=1; i<n; ++i) {
			j = in.nextInt();
			k = in.nextInt();
			E[j].add(k);
			E[k].add(j);
		}

		dfs(1, 0, a[1]);

		out.println(ans);
	}

	private void dfs(int u, int fa, int cn) {
		int sz = E[u].size(), v;
		int c = 0, cn_;

		if (cn > m)
			return ;

		for (int i=0; i<sz; ++i) {
			v = E[u].get(i);
			if (v == fa)
				continue;
			++c;
			cn_ = a[v]>0 ? cn+1 : 0;
			dfs(v, u, cn_);
		}

		if (c==0 && cn<=m)
			++ans;
	}
}

class adj {
	ArrayList<Integer> m;

	public adj() {
		m = new ArrayList<Integer>();
	}

	public int size() {
		return m.size();
	}

	public int get(int x) {
		return m.get(x);
	}

	public void add(int x) {
		m.add(x);
	}
}

class InputReader {
	public BufferedReader reader;
	public StringTokenizer tokenizer;

	public InputReader(InputStream stream) {
		reader = new BufferedReader(new InputStreamReader(stream), 32768);
		tokenizer = null;
	}

	public String next() {
		while (tokenizer==null || !tokenizer.hasMoreTokens()) {
			try {
				tokenizer = new StringTokenizer(reader.readLine());
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return tokenizer.nextToken();
	}

	public int nextInt() {
		return Integer.parseInt(next());
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;

public class C {
    static int n;
    static int m;
    static boolean[] hasCat;
    static List<Set<Integer>> graph;
    static int answer;
    public static void main(String[] args) {
        Scanner scanner = new Scanner();

        n = scanner.nextInt();
        m = scanner.nextInt();
        hasCat = new boolean[n];
        graph = new ArrayList<>();
        answer = 0;

        for (int i = 0; i < n; i++) {
            hasCat[i] = scanner.nextInt() == 1;
            graph.add(new HashSet<Integer>());
        }
        for (int i = 0; i < n-1; i++) {
            int x = scanner.nextInt()-1;
            int y = scanner.nextInt()-1;
            if (x > y) {
                int temp = x;
                x = y;
                y = temp;
            }
            graph.get(x).add(y);
//            Trying to see if this works one way
//            graph.get(y).add(x);
        }

        search(0, 0);
        System.out.println(answer);
    }

    static void search(int vertex, int catsSoFar) {
        if (hasCat[vertex]) {
            catsSoFar++;
        } else {
            catsSoFar = 0;
        }
        if (catsSoFar > m) {
            return;
        }

        if (isLeaf(vertex)) {
            answer++;
        } else {
            for (int child : graph.get(vertex)) {
                search(child, catsSoFar);
            }
        }
    }

    static boolean isLeaf(int vertex) {
        return graph.get(vertex).isEmpty();
    }

    public static class Scanner {
        BufferedReader br;
        StringTokenizer st;

        public Scanner(Reader in) {
            br = new BufferedReader(in);
        }

        public Scanner() { this(new InputStreamReader(System.in)); }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() { return Integer.parseInt(next()); }
        long nextLong() { return Long.parseLong(next()); }
        double nextDouble() { return Double.parseDouble(next()); }

        // Slightly different from java.util.Scanner.nextLine(),
        // which returns any remaining characters in current line,
        // if any.
        String readNextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;

public class C {
    static int n;
    static int m;
    static boolean[] hasCat;
    static List<Set<Integer>> graph;
    static int answer;
    public static void main(String[] args) {
        Scanner scanner = new Scanner();

        n = scanner.nextInt();
        m = scanner.nextInt();
        hasCat = new boolean[n];
        graph = new ArrayList<>();
        answer = 0;

        for (int i = 0; i < n; i++) {
            hasCat[i] = scanner.nextInt() == 1;
            graph.add(new HashSet<Integer>());
        }
        for (int i = 0; i < n-1; i++) {
            int x = scanner.nextInt()-1;
            int y = scanner.nextInt()-1;

            graph.get(x).add(y);
            graph.get(y).add(x);
        }

        search(0, 0, -1);
        System.out.println(answer);
    }

    static void search(int vertex, int catsSoFar, int parent) {
        if (hasCat[vertex]) {
            catsSoFar++;
        } else {
            catsSoFar = 0;
        }
        if (catsSoFar > m) {
            return;
        }

        if (isLeaf(vertex)) {
            answer++;
        } else {
            for (int child : graph.get(vertex)) {
                if (child != parent) {
                    search(child, catsSoFar, vertex);
                }
            }
        }
    }

    static boolean isLeaf(int vertex) {
        return graph.get(vertex).size() == 1 && vertex != 0;
    }

    public static class Scanner {
        BufferedReader br;
        StringTokenizer st;

        public Scanner(Reader in) {
            br = new BufferedReader(in);
        }

        public Scanner() { this(new InputStreamReader(System.in)); }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() { return Integer.parseInt(next()); }
        long nextLong() { return Long.parseLong(next()); }
        double nextDouble() { return Double.parseDouble(next()); }

        // Slightly different from java.util.Scanner.nextLine(),
        // which returns any remaining characters in current line,
        // if any.
        String readNextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;

public class C {
    static int n;
    static int m;
    static boolean[] hasCat;
    static List<Set<Integer>> graph;
    static int answer;
    public static void main(String[] args) {
        Scanner scanner = new Scanner();

        n = scanner.nextInt();
        m = scanner.nextInt();
        hasCat = new boolean[n];
        graph = new ArrayList<>();
        answer = 0;

        for (int i = 0; i < n; i++) {
            hasCat[i] = scanner.nextInt() == 1;
            graph.add(new HashSet<Integer>());
        }
        for (int i = 0; i < n-1; i++) {
            int x = scanner.nextInt()-1;
            int y = scanner.nextInt()-1;
            graph.get(x).add(y);
//            Trying to see if this works one way
//            graph.get(y).add(x);
        }

        search(0, 0);
        System.out.println(answer);
    }

    static void search(int vertex, int catsSoFar) {
        if (hasCat[vertex]) {
            catsSoFar++;
        } else {
            catsSoFar = 0;
        }
        if (catsSoFar > m) {
            return;
        }

        if (isLeaf(vertex)) {
            answer++;
        } else {
            for (int child : graph.get(vertex)) {
                search(child, catsSoFar);
            }
        }
    }

    static boolean isLeaf(int vertex) {
        return graph.get(vertex).isEmpty();
    }

    public static class Scanner {
        BufferedReader br;
        StringTokenizer st;

        public Scanner(Reader in) {
            br = new BufferedReader(in);
        }

        public Scanner() { this(new InputStreamReader(System.in)); }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() { return Integer.parseInt(next()); }
        long nextLong() { return Long.parseLong(next()); }
        double nextDouble() { return Double.parseDouble(next()); }

        // Slightly different from java.util.Scanner.nextLine(),
        // which returns any remaining characters in current line,
        // if any.
        String readNextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}


import java.io.*;
import java.util.*;

public class Solution {

    private static int n, m, cnt;
    private static boolean[] cat;
    private static Map<Integer, List<Integer>> adjacency;

    private static void dfs(int cur, int prev, int catCnt) {
        if (cat[cur]) {
            catCnt++;
            if (catCnt > m) return;
        } else
            catCnt = 0;

        List<Integer> list = adjacency.get(cur);
        if (list.size() == 1) {
            cnt++;
            return;
        }

        for (Integer i: list)
            if (i != prev) dfs(i, cur, catCnt);
    }

    private static void solve(InputReader in, OutputWriter out) {
        n = in.nextInt();
        m = in.nextInt();

        cat = new boolean[n + 1];
        for (int i = 1; i <= n; i++)
            if (in.nextInt() == 1) cat[i] = true;

        adjacency = new HashMap<Integer, List<Integer>>();
        int x, y;

        for (int i = 0; i < n - 1; i++) {
            x = in.nextInt();
            y = in.nextInt();

            if (!adjacency.containsKey(x)) adjacency.put(x, new ArrayList<Integer>());
            if (!adjacency.containsKey(y)) adjacency.put(y, new ArrayList<Integer>());

            adjacency.get(x).add(y);
            adjacency.get(y).add(x);
        }

        cnt = 0;
        dfs(1, 0, 0);
        out.print(cnt);
    }

    public static void main(String[] args) {
        InputReader in = new InputReader(System.in);
        OutputWriter out = new OutputWriter(System.out);
        solve(in, out);
        in.close();
        out.close();
    }

    private static class InputReader {
        private BufferedReader br;
        private StringTokenizer st;

        InputReader(InputStream is) {
            br = new BufferedReader(new InputStreamReader(is));
            st = null;
        }

        String nextLine() {
            String line = null;
            try {
                line = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return line;
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                String line = nextLine();
                if (line == null) return null;
                st = new StringTokenizer(line);
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        void close() {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static class OutputWriter {
        BufferedWriter bw;

        OutputWriter(OutputStream os) {
            bw = new BufferedWriter(new OutputStreamWriter(os));
        }

        void print(int i) {
            print(Integer.toString(i));
        }

        void println(int i) {
            println(Integer.toString(i));
        }

        void print(long l) {
            print(Long.toString(l));
        }

        void println(long l) {
            println(Long.toString(l));
        }

        void print(double d) {
            print(Double.toString(d));
        }

        void println(double d) {
            println(Double.toString(d));
        }

        void print(boolean b) {
            print(Boolean.toString(b));
        }

        void println(boolean b) {
            println(Boolean.toString(b));
        }

        void print(char c) {
            try {
                bw.write(c);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        void println(char c) {
            println(Character.toString(c));
        }

        void print(String s) {
            try {
                bw.write(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        void println(String s) {
            print(s);
            print('\n');
        }

        void close() {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}