A. Divide it!
题目链接:http://codeforces.com/contest/1176/problem/A
题目
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
Copy
7
1
10
25
30
14
27
1000000000000000000
Output
0
4
6
6
-1
6
72
题意
给你一个数n,如果能整除2,则n变成n/2;如果能整除3,则n变成(2/3)*n;如果能整除5,则变成(4/5)*n;
如果n能经过上述任意操作使n达到1,输出操作步数最小值,如果得不到1,输出-1.
思路
经过推算,
一个数如果能被2整除,那么可以先一直乘以1/2,
能够整除3的可以再一直乘以2/3,
能够整除5的可以再一直乘4/5,
和既能先乘以1/2的再乘2/3的再乘1/2的步数相同,所以代码就好实现了。
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int maxn=1e6+10; int main() { int n; cin>>n; ll x; for(int i=0;i<n;i++) { cin>>x; if(x==1) puts("0"); else { ll sum=0; bool flag=true; while(1) { if ((x / 2) * 2 == x) { while ((x / 2) * 2 == x) { // cout<<"2fff"; x = x / 2; // cout<<x; sum++; } } else if ((x / 3) * 3 == x) { while ((x / 3) *3 == x) { x = (x * 2) / 3; sum++; } } else if ((x / 5) * 5 == x) { while ((x / 5) * 5 == x) { x = (x * 4) / 5; sum++; } } else if(x==1) break; else { flag=false; break; } } if(!flag) cout<<"-1"<<endl; else cout<<sum<<endl; } } return 0; }
原文地址:https://www.cnblogs.com/Vampire6/p/11001256.html