Two little greedy bears have found two pieces of cheese in the forest of weight a and b grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: "Little bears, wait a little, I want to make your pieces equal" "Come off it fox, how are you going to do that?", the curious bears asked. "It's easy", said the fox. "If the mass of a certain piece is divisible by two, then I can eat exactly a half of the piece. If the mass of a certain piece is divisible by three, then I can eat exactly two-thirds, and if the mass is divisible by five, then I can eat four-fifths. I'll eat a little here and there and make the pieces equal".
The little bears realize that the fox's proposal contains a catch. But at the same time they realize that they can not make the two pieces equal themselves. So they agreed to her proposal, but on one condition: the fox should make the pieces equal as quickly as possible. Find the minimum number of operations the fox needs to make pieces equal.
The first line contains two space-separated integers a and b (1 ≤ a, b ≤ 109).
If the fox is lying to the little bears and it is impossible to make the pieces equal, print -1. Otherwise, print the required minimum number of operations. If the pieces of the cheese are initially equal, the required number is 0.
15 20
3
14 8
-1
6 6
0
#include <stdio.h>
#include <stdlib.h>
int main(void){
int a, b;
while(scanf("%d%d",&a,&b)!=EOF){
int count=0;
if (a == b){
printf("0\n");
continue;
}
int c[4]={0},d[4]={0};
while (!(a % 2)) a /= 2, c[0]++;
while (!(a % 3)) a /= 3, c[1]++;
while (!(a % 5)) a /= 5, c[2]++;
while (!(b % 2)) b /= 2, d[0]++;
while (!(b % 3)) b /= 3, d[1]++;
while (!(b % 5)) b /= 5, d[2]++;
if (a != b){
printf("-1\n");
continue;
}
for (int i=0; i<3; i++)
count += abs(c[i] - d[i]);
printf("%d\n",count);
}
}
再贴上大神的代码,学习可学习之处:
#include <stdio.h>
#include <stdlib.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define Rep(i, n) for (int i = 1; i <= (n); ++i)
#define clr(x, a) memset(x, (a), sizeof x)//这种使用宏的方法值得学习!!!
int max(int a,int b){
return a>b?a:b;
}
int min(int a,int b){
return a>b?b:a;
}
typedef long long ll;//简洁!!!
int c[10], d[10];
int main(void) {
int a, b;
scanf("%d%d",&a,&b);
int t = a, y = b;
while (t % 2 == 0) t /= 2, ++c[0];
while (t % 3 == 0) t /= 3, ++c[1];
while (t % 5 == 0) t /= 5, ++c[2];
while (y % 2 == 0) y /= 2, ++d[0];
while (y % 3 == 0) y /= 3, ++d[1];
while (y % 5 == 0) y /= 5, ++d[2];
if (t != y) puts("-1");//为什么?
else {
int ret = 0;
rep(i, 3) ret += max(c[i], d[i]) - min(c[i], d[i]);
printf("%d\n",ret);
}
return 0;
}