Codeforces Round #653 (Div. 3) B. Multiply by 2, divide by 6(暴力、思维)

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 ------------ 36

Note:

Consider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer 1511654415116544 :

  1. Divide by 66 and get 25194242519424 ;
  2. divide by 66 and get 419904419904 ;
  3. divide by 66 and get 6998469984 ;
  4. divide by 66 and get 1166411664 ;
  5. multiply by 22 and get 2332823328 ;
  6. divide by 66 and get 38883888 ;
  7. divide by 66 and get 648648 ;
  8. divide by 66 and get 108108 ;
  9. multiply by 22 and get 216216 ;
  10. divide by 66 and get 3636 ;
  11. divide by 66 and get 66 ;
  12. divide by 66 and get 11 .
展开阅读全文
©️2020 CSDN 皮肤主题: 黑客帝国 设计师: 上身试试 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值