Codeforces Round #565 (Div. 3)A. Divide it!

本文探讨了一个算法问题,目标是最小化操作次数将任意正整数n转换为1。允许的操作包括:若n能被2整除,则用n/2替换n;若n能被3整除,则用2*(n/3)替换n;若n能被5整除,则用4*(n/5)替换n。文章详细解释了如何通过这些操作达到目标,并提供了一个实例演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
inputCopy
7
1
10
25
30
14
27
1000000000000000000
outputCopy
0
4
6
6
-1
6
72

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<ctime>
#include<iostream>
#include<algorithm>
#include<map>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<string>
#define ll long long
#define dd double
using namespace std;

int main() {
	ios::sync_with_stdio(0);
	ll t;
	cin >> t;
	while (t--) {
		ll n; cin >> n;
		ll sum = 0;
		ll flag = 0;
		while (n != 1) {
			if (n % 2 == 0) {
				n = n / 2;
				sum++;
			}
			else if(n % 3 == 0 && n % 5 == 0) {
				n = min(((n / 3) * 2),((n / 5) * 4));
				sum++;
			}
			else if (n % 3 == 0) {
				n = n / 3 * 2;
				sum++;
			}
			else if (n % 5 == 0) {
				n = n / 5 * 4;
				sum++;
			}
			else {
				flag = 1;
				cout << "-1" << endl;
				break;
			}
		}
		if (flag == 0) {
			cout << sum << endl;
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值