题目
A. Divide it!
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an integer n.
You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:
Replace n with n2 if n is divisible by 2;
Replace n with 2n3 if n is divisible by 3;
Replace n with 4n5 if n is divisible by 5.
For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation.
Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1≤q≤1000) — the number of queries.
The next q lines contain the queries. For each query you are given the integer number n (1≤n≤1018).
Output
Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it.
Example
input
7
1
10
25
30
14
27
1000000000000000000
output
0
4
6
6
-1
6
72
题目理解
题目提供了三种对n的计算方法:
- 当n可以被2整除时,n=n/2;
- 当n可以被3整除时,n=n*2/3;
- 当n可以被5整除时,n=n*4/5。
求n通过计算变成1的最小步骤。如果n无法通过以上三种计算方式得到1的话,则输出-1.
解题思路
直接模拟计算方法操作,因为n/2 > n2/3 > n4/5,所以先判断是否能被2整除,再判断是否能被3整除,最后才判断是否能被5整除,计算最小步骤。
代码如下(python)
q = int(input().strip())
while q:
q-=1
n = int(input().strip())
cnt = 0
while n != 1:
cnt += 1
if n % 2 == 0:
n = n // 2
elif n % 3 == 0:
n = n * 2 // 3
elif n % 5 == 0:
n = n * 4 // 5
else:
cnt = -1
break
print(cnt)