Multiply by 2, divide by 6
题目大意:(文末有原题)
给出一个整数,计算通过几次 *2 或者 /6 会得到1;
思路:
要求通过*2 或者 /6得到1,实际上其实是/3 或者 /6,如果可以则一定要满足含有因子3,所以就每次判断是否含有3即可,如果不含,则通过操作一定不会得到1,否则就暴力执行操作;
代码:
#include <iostream> using namespace std; typedef long long ll; int main() { int t; cin >> t; while(t--) { ll n, s = 0; cin >> n; while(1) { if(n % 3 && n % 6) //如果出现不能整除的情况,之后就一定不能得到1了(因为操作时*2或者/6,如果不满足不论怎么操作都不会满足) break; if(n == 1) break; if(n % 6 == 0){ n /= 6; s++; }else if(n % 3 == 0) { //n *= 2, n /= 6; n /= 3; s += 2; } } if(n == 1) cout << s << endl; else cout << "-1" << endl; } return 0; }
原题:
题目:
You are given an integer n. In one move, you can either multiply n by two or divide nn by 6 (if it is divisible by 6 without the remainder).
Your task is to find the minimum number of moves needed to obtain 1 from nn or determine if it's impossible to do that.
You have to answer tt independent test cases.
输入:
The first line of the input contains one integer tt (1≤t≤2⋅10^4) — the number of test cases. Then tt test cases follow.
The only line of the test case contains one integer nn (1≤n≤10^9).
输出:
For each test case, print the answer — the minimum number of moves needed to obtain 1 from n if it's possible to do that or -1 if it's impossible to obtain 1 from n.
样例:
Input: Output:
7
1 ------------------------- 0
2 ------------------------- -1
3 ------------------------- 2
12 ------------------------ -1
12345 ------------------- -1
15116544 -------------- 12
387420489 ------------ 36Note:
Consider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer 1511654415116544 :
- Divide by 66 and get 25194242519424 ;
- divide by 66 and get 419904419904 ;
- divide by 66 and get 6998469984 ;
- divide by 66 and get 1166411664 ;
- multiply by 22 and get 2332823328 ;
- divide by 66 and get 38883888 ;
- divide by 66 and get 648648 ;
- divide by 66 and get 108108 ;
- multiply by 22 and get 216216 ;
- divide by 66 and get 3636 ;
- divide by 66 and get 66 ;
- divide by 66 and get 11 .