HDU 5505 GT and numbers
2016-02-02 21:26
369 查看
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.
T≤1000, 1≤N≤1000000,1≤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
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; }
相关文章推荐
- nodejs学习笔记二——链接mongodb
- nodejs学习笔记二——链接mongodb
- hdu 2509 Be the Winner 尼姆博奕
- HDU1004(枚举)
- hdu——2019数列有序!
- http://www.osyunwei.com/archives/4788.html
- java 双向链表实现双端队列
- Maven学习 (五) Elipse中发布一个Maven项目到Tomcat
- 蓝桥杯 基础练习 字母图形 有瑕丝
- 莫比乌斯反演的学习(HDU1695)
- 九度[1101]计算表达式
- 《machine learning with spark》学习笔记--推荐模型
- Python实现kNN(k邻近算法)
- 【linux】如何查看和解压缩rpm文件内容
- Elasticsearch进化史
- java集合基础
- canvas-线条
- 没有上司的舞会--树形DP
- python小白-day4递归和算法基础
- hdu1325 Is It A Tree?(有向图并查集)