HDU 5505 GT and numbers

来源:互联网 发布:mac 打开icloud 编辑:程序博客网 时间:2024/04/27 07:07

GT and numbers

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


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.

T10001N1000000,1M263.

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
31 11 22 4
 

Sample Output
0-11
 

Source
BestCoder Round #60
 
很好的一道题目。
大体题意:
给你两个数N.M,N可以乘N的因子变成一个新的N,问多少步可以使得N等于M,(注意是相等,不是M的倍数)
如果不可能相等,则输出-1,
大体思路:
1.既然N通过乘一系列因子,变成M,所以M一定是N的整数倍,所以一开始先判断 如果N > M或者 M % N != 0就输出-1.
2.那一系列因子的乘积一定是M / N,所以为了使N快速到达M,N 一定使乘以temp = gcd(N,M/N),这样乘下去,如果temp不是1,那么一定可以乘到M,如果乘着乘着发现temp是1的话,那就说明永远不可能乘到M,也输出-1,否则输出计数sum就行了!

需要注意 M的最大值是2^63,long long是取不到的,所以要开unsigned long long;

代码如下:

#include<iostream>#include<cstdio>#include<map>#include<set>#include<stack>#include<queue>#include<vector>#include<string>#include<cstring>#include<cmath>#include<cstdlib>#include<cctype>#include<algorithm>#define mem(x) memset(x,0,sizeof(x));#define mem1(x) memset(x,-1,sizeof(x));using namespace std;const int maxn = 10000 + 10;const int maxt = 100 + 10;const double eps = 1e-8;const double pi = acos(-1.0);const int INF = 1e8;typedef long long ll;typedef unsigned long long llu;llu gcd(llu a,llu b){    if (!b)return a;    else return gcd(b,a%b);}int main(){    int T;    cin >> T;    while(T--){        llu n,m,temp=2;        cin >> n >> m;        if (n==m)cout << 0 << endl;        else if (n > m || m % n != 0 || (n==1 && m > 1))cout << -1 << endl;        else {            int sum = 0;            while(n<m && temp != 1){                temp = gcd(n,m/n);                n*=temp;                sum++;            }            if (temp == 1)cout << -1 << endl;            else cout << sum << endl;        }    }    return 0;}





0 0
原创粉丝点击