codeforces题目之1176 A. Divide it!

题目

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的计算方法:

  1. 当n可以被2整除时,n=n/2;
  2. 当n可以被3整除时,n=n*2/3;
  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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值