题目:
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.
解题思路:
对a,b因式分解,看含有几个2,几个3,几个5。即a=2^a1*3^a2*5^a3*a4,b=2^b1*3^b2*5^b3*b4。比较a4,b4若不同返回-1,若相同则操作次数为:|a1-b1|+|a2-b2|+|a3-b3|。
AC代码:
#include <iostream>;
using namespace std;
int power(long int &a,int b){
int power=0;
while(a%b==0){
power++;
a=a/b;
}
return power;
}
int main(){
long int a,b;
int power2[2]={0,0},power3[2]={0,0},power5[2]={0,0};
int times;
cin>>a>>b;
power2[0]=power(a,2);
power2[1]=power(b,2);
power3[0]=power(a,3);
power3[1]=power(b,3);
power5[0]=power(a,5);
power5[1]=power(b,5);
if(a!=b){
cout<<-1;
return 0;
}
times=abs(power2[0]-power2[1])+abs(power3[0]-power3[1])+abs(power5[0]-power5[1]);
cout<<times;
}