微软预科生计划-探星夏令营在线测试
时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
Give you two integers P and Q. Let all divisors of P be X-coordinates. Let all divisors of Q be Y-coordinates.
For example, when P=6 and Q=2, we can get the coordinates (1,1) (1,2) (2,1) (2,2) (3,1) (3,2) (6,1) (6,2).
You should print all possible coordinates in the order which is first sorted by X-coordinate when coincides, sorted by Y-coordinate.
输入
One line with two integers P and Q(1 <= P, Q <= 10000).
输出
The output may contains several lines , each line with two integers Xi and Yi, denoting the coordinates.
样例输入
6 2
样例输出
1 1
1 2
2 1
2 2
3 1
3 2
6 1
6 2
这个题目就是要找出输入的P和Q的所有约数,然后把约数按照先P后Q的顺序,从小到大排列所有组合”Pi Qi”,并输出。主要任务是找约数,其实找到数的一半就行。也就是说,找P的约数,只要从1找到P/2就行了。由于不知道每个约数的多少。因此使用了vector容器,找到一个 塞进去一个。P和Q都找完了以后,按照首先按照P的大小排列,再按照Q的大小排列的原则,输出结果。
下面是AC的代码(leetcode风格):
//Coordinates
#include<iostream>
#include<string>
#include<stdio.h>
#include<vector>
using namespace std;
vector<int> X;//用来存放P的约数
vector<int> Y;//用来存放Q的约数
class Solution {
public:
int FindHi()
{
int N = 0, M = 0;
cin >> N >> M;//输入P Q
for (int i = 1; i <= N/2; i++)//将P的约数塞入
{
if (!(N%i)) {
X.push_back(i);
}
}
X.push_back(N);//记得P自己也是约数
for (int i = 1; i <= M / 2; i++)//将Q的约数塞入
{
if (!(M%i)) {
Y.push_back(i);
}
}
Y.push_back(M);//记得Q自己也是约数
for (int i = 0; i < X.size(); i++)//P优先
{
for (int j = 0; j < Y.size(); j++)//Q其次
{
cout << X[i] << " " << Y[j] << endl;//注意中间有空格
}
}
return 0;
}
};
int main()
{
Solution sol;
sol.FindHi();
system("pause");
return 0;
}
如果有问题,欢迎讨论