hdu5505-GT and numbers-(贪心+gcd+唯一分解定理)

Posted shoulinniao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu5505-GT and numbers-(贪心+gcd+唯一分解定理)相关的知识,希望对你有一定的参考价值。

GT and numbers

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2772    Accepted Submission(s): 688


Problem Description
You are given two numbers N and M.

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

Work out how many steps can N be equal to M at least.

If N can‘t be to M forever,print ?1 .
 

 

Input
In the first line there is a number T. T is the test number.

In the next T lines there are two numbers N and M .

T1000 , 1N1000000 ,1M2^63 .

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的因子数,求最少乘几次

坑1:m需要用无符号long long定义

坑2:n的因子会变,变多变大
用r表示需要乘的总数,择优,每次选r和n的gcd,这样每次乘得多,次数就少,同时更新r和n
如果遇到r!=1,gcd=1证明需要乘的数 包含 n没有的因子,退出。

 

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<string>
#include<vector>
#include<iostream>
#include<cstring>
#define inf 0x3f3f3f3f
using namespace std;
#define ll unsigned long long
const int p=10007;
const int maxx=1e6+5;
ll n,m;///坑1:无符号long long才放得下
int step;
ll gcd(ll a,ll b)
{
    if(b==0) return a;
    return gcd(b,a%b);
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        cin>>n>>m;
        step=0;
        if(n==m) printf("0
");
        else if(n>m || m%n) printf("-1
");
        else
        {
            ll r=m/n;///r表示 n还要 乘 一个数 变成m
            ll d;
            bool flag=true;
            while(r!=1)
            {
                d=gcd(r,n);
                if(d==1)///出现这种情况,r!=1,和n没有共同因子,则表示m中含有n中不含有的质因子
                {
                    flag=false;
                    break;
                }
                r=r/d;
                n=n*d;///坑2:每次n会变大,因子会更新
                step++;
            }
            if(flag)
                cout<<step<<endl;
            else printf("-1
");
        }
    }
    return 0;
}

 

 

 























以上是关于hdu5505-GT and numbers-(贪心+gcd+唯一分解定理)的主要内容,如果未能解决你的问题,请参考以下文章

HDU-6216 A Cubic number and A Cubic Number[二分]

HDU 6216 A Cubic number and A Cubic Number数学思维+枚举/二分

HDU 5611 Baby Ming and phone number

hdu 6216 A Cubic number and A Cubic Number数学

Regular Number hdu-5972(bitset+Shift-And算法)

hdu 6216 A Cubic number and A Cubic Number