【HDU - 5505】GT and numbers 【gcd + 算数基本定理】

You are given two numbers NN and MM.

Every step you can get a new NN in the way that multiply NN by a factor of NN.

Work out how many steps can NN be equal to MM at least.

If N can’t be to M forever,print −1−1.
Input
In the first line there is a number TT.TT is the test number.

In the next TT lines there are two numbers NN and MM.

T≤1000T≤1000, 1≤N≤10000001≤N≤1000000,1≤M≤2631≤M≤263.

Be careful to the range of M.

You’d better print the enter in the last line when you hack others.

You’d better not print space in the last of each line when you hack others.
Output
For each test case,output an answer.
Sample Input
3
1 1
1 2
2 4
Sample Output
0
-1
1
题意 : 给n和m,每次操作可以将n变为n*其因子,问是否可以从n变到m,不可以输出-1,可以的话输出最小的操作次数。

分析: 想一下,什么样的数字n才可以不断乘自己的因子,然后变成m,提示一下,算数基本定理的方向考虑-TAT 。如果n的质因子中有一个m没有,这肯定不用想了吧,不管怎么乘一定是不会变为m的。 其实就是m的所有的质因子,n都要有,同时n的每个质因子的指数还都不能够大于对应m中的指数。 好了,现在我们已经知道基本的条件,那怎么求最小的次数呢?我们可以先用t=m/n得到m里去除n中部分质因子的指数,然后求t和n的gcd,这个时候得到的肯定是目前能够乘的最大因子,不断执行下去就行了。ok,看代码吧。

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int>pii;
#define first fi
#define second se
#define  LL long long
#define fread() freopen("in.txt","r",stdin)
#define fwrite() freopen("out.txt","w",stdout)
#define CLOSE() ios_base::sync_with_stdio(false)

const int MAXN = 1e5;
const int MAXM = 1e6;
const int mod = 1e9+7;
const int inf = 0x3f3f3f3f;

unsigned long long gcd(unsigned long long a,unsigned long long b ){
    return b==0?a:gcd(b,a%b);
}
int main(){
    CLOSE();
//  fread();
//  fwrite();
    int T ;cin>>T;
    while(T--){
        unsigned long long n,m;
        cin>>n>>m; //  因为m 2^63 所以要用无符号型longlong来存
        if(n==m) cout<<0<<endl;
        else if(m<n||m%n)  cout<<-1<<endl; 
        else {// m%n!=0 表明n的质因子中有至少一个与m的质因子不同
            int cnt=0;int flag=1;
            while(n!=m){
                unsigned long long t=gcd(n,m/n);//得到当前可以乘的最大因子
                if(n>m||t==1) {
                    flag=0;
                    break;
                }
                n*=t;
                cnt++;
            }
            if(flag) cout<<cnt<<endl;
            else cout<<-1<<endl;
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值