Codeforces 371B Fox Dividing Cheese(简单数论)

题目链接 Fox Dividing Cheese

思路:求出两个数a和b的最大公约数g,然后求出a/g,b/g,分别记为c和d。

   然后考虑c和d,若c或d中存在不为2,3,5的质因子,则直接输出-1(根据题目要求)

           计算出c = (2 ^ a2) * (3 ^ a3) * (5 ^ a5)      d = (2 ^ b2) * (3 ^ b3) * (5 ^ b5)

   那么答案就是a2 + a3 + a5 + b2 + b3 + b5

#include <bits/stdc++.h>

using namespace std;

int a, b;
int n, m, x;
int a2, a3, a5, b2, b3, b5;

int gcd(int a, int b){
    return b == 0 ? a : gcd(b, a % b);
}

int main(){

    scanf("%d%d", &n, &m);
    if (n == m){puts("0"); return 0;}
    x = gcd(n, m);

    a = n / x, b = m / x;
    while (a % 2 == 0) { a /= 2, ++a2;}
    while (a % 3 == 0) { a /= 3, ++a3;}
    while (a % 5 == 0) { a /= 5, ++a5;}

    while (b % 2 == 0) { b /= 2, ++b2;}
    while (b % 3 == 0) { b /= 3, ++b3;}
    while (b % 5 == 0) { b /= 5, ++b5;}

    if (a > 1 || b > 1){
        puts("-1");
        return 0;
    }
    
    printf("%d\n", a2 + a3 + a5 + b2 + b3 + b5);
    return 0;

}

 

posted @ 2017-01-31 20:23  cxhscst2  阅读(239)  评论(0编辑  收藏  举报