Problem Statement
You are given a sequence of positive integers: A=(a_1,a_2,\ldots,a_N)A=(a1,a2,…,aN).
You can choose and perform one of the following operations any number of times, possibly zero.
- Choose an integer ii such that 1 \leq i \leq N1≤i≤N and a_iai is a multiple of 22, and replace a_iai with \frac{a_i}{2}2ai.
- Choose an integer ii such that 1 \leq i \leq N1≤i≤N and a_iai is a multiple of 33, and replace a_iai with \frac{a_i}{3}3ai.
Your objective is to make AA satisfy a_1=a_2=\ldots=a_Na1=a2=…=aN.
Find the minimum total number of times you need to perform an operation to achieve the objective. If there is no way to achieve the objective, print -1
instead.
Constraints
- 2 \leq N \leq 10002≤N≤1000
- 1 \leq a_i \leq 10^91≤ai≤109
- All values in the input are integers.
Input
The input is given from Standard Input in the following format:
NN a_1a1 a_2a2 \ldots… a_NaN
Output
Print the answer.
Sample Input 1 Copy
Copy
3 1 4 3
Sample Output 1 Copy
Copy
3
Here is a way to achieve the objective in three operations, which is the minimum needed.
- Choose an integer i=2i=2 such that a_iai is a multiple of 22, and replace a_2a2 with \frac{a_2}{2}2a2. AA becomes (1,2,3)(1,2,3).
- Choose an integer i=2i=2 such that a_iai is a multiple of 22, and replace a_2a2 with \frac{a_2}{2}2a2. AA becomes (1,1,3)(1,1,3).
- Choose an integer i=3i=3 such that a_iai is a multiple of 33, and replace a_3a3 with \frac{a_3}{3}3a3. AA becomes (1,1,1)(1,1,1).
Sample Input 2 Copy
Copy
3 2 7 6
Sample Output 2 Copy
Copy
-1
There is no way to achieve the objective.
Sample Input 3 Copy
Copy
6 1 1 1 1 1 1
Sample Output 3 Copy
Copy
0
题解:要想所有的数能变成同一个数,那它们的因素只可能有2 , 3 以及 它们的最大公因数 ,注意最大公因数也可能是2,3的倍数。
因此: 1.所有数的求最大公因数
2.数组元素除最大公因数,此时不数组中不可能存在一个元素(不等于1),可以使得数组中每个数都等于该元素.
3.因此最小的操作次数是除去最大公因数后到1 的操作次数之和。
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <iostream>
#include <cmath>
using namespace std;
typedef long long ll;
ll n, p, ans;
ll a[1100];
long long gcd(long long a, long long b)
{
while (b ^= a ^= b ^= a %= b);
return a;
}
int main() {
cin >> n;
for (ll i = 1; i <= n; i++) {
cin >> a[i];
}
p = a[1];
for (ll i = 2; i <= n; i++) {
p = gcd(a[i], p);//找最大公因数
}
for (ll i = 1; i <= n; i++) {
ll x = a[i] / p;
while (x % 2 == 0) {
x /= 2;
ans++;
}
while (x % 3 == 0) {
x /= 3;
ans++;
}
if (x != 1) {
ans = -1;
break;
}
}
printf("%lld\n", ans);
return 0;
}