HDU 4320 Arcane Numbers 1

HDU 4320 Arcane Numbers 1 :http://acm.hdu.edu.cn/showproblem.php?pid=4320

题面:

Arcane Numbers 1

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3017    Accepted Submission(s): 957


Problem Description
Vance and Shackler like playing games. One day, they are playing a game called "arcane numbers". The game is pretty simple, Vance writes down a finite decimal under base A, and then Shackler translates it under base B. If Shackler can translate it into a finite decimal, he wins, else it will be Vance’s win. Now given A and B, please help Vance to determine whether he will win or not. Note that they are playing this game using a mystery language so that A and B may be up to 10^12.
 

Input
The first line contains a single integer T, the number of test cases.
For each case, there’s a single line contains A and B.
 

Output
For each case, output “NO” if Vance will win the game. Otherwise, print “YES”. See Sample Output for more details.
 

Sample Input
   
   
   
   
3 5 5 2 3 1000 2000
 

Sample Output
   
   
   
   
Case #1: YES Case #2: NO Case #3: YES

题目大意:

问一个有限小数n在A,B两种进制下能否实现相互转换,能则输出YES,否则输出NO


题目分析:

对于一个在任意进制下的数n,包括整数和小数两个部分,对于这两个部分分别遵循“整数除基倒取余”和“小数乘基正取整”原则。

则对于整数部分一定可以实现两种不同进制之间的转换,而对于小数部分,在多次乘基之后,能实现小数部分变为0,即可实现进制转换。设其为x,且小数部分共有k位,第i位上的数字为ai,则x可以表示为:

X=a1*A^-1+a2*A^-2+a3*A^-3+...+ak*A^-k

则只有在所乘数中出现A^k,才会实现进制转换,即判断B^h(h可无限大)中是否有因子A^k。

由算数基本定理,A^k的素因子一定和A的素因子相同。

所以,只要B中包含A中的所有的素因子,就一定能找到h,是两种进制之间可以实现相互转换。

求解方法如下:

若A与B不互素,则要判段B中是否含有A/gcd(A,B)的所有素因子;若A与B互素,若A==1,则B中包含A中所有的素因子。


代码实现:

#include <iostream>
#include <cstdio>

using namespace std;

long long gcd(long long a,long long b)
{
    if(b==0)
    return a;
    else return gcd(b,a%b);
}

int main()
{
    int T;
    int casenum=0;
    long long a,b;
    long long d;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld%lld",&a,&b);
        d=gcd(a,b);
        while(d!=1)
        {
            a/=d;
            d=gcd(a,b);
        }
        if(a==1)
        printf("Case #%d: YES\n",++casenum);
        else
        printf("Case #%d: NO\n",++casenum);
    }
    return 0;
}


你可能感兴趣的:(进制转换,最大公约数)