1186 : Coordinates
时间限制: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(Y坐标).
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的约数p,q能够组成的不重复数字对
(p,q)
解题思路:- 本题中需要求出P,Q所有约数组成的数字对,因此我们需要先将P,Q两个数字所有的约数分别找出来,再依次组合后输出。求解一个数字P的所有约数,
可以依次枚举1..P分别进行检查是否能够被P整除,也可以降低复杂度只枚举1..sqrt(P),具体实现可以参考如下伪代码: -
// 枚举 1.. P
p_count = 0
For i = 1 .. P
If (P mod i == 0) Then
p_divisors[p_count] = i
p_count = p_count + 1
End If
End For
// 枚举 1 .. sqrt(P)
p_count = 0
For i = 1 .. sqrt(P)
If (P mod i == 0) Then
p_divisors[p_count] = i
p_count = p_count + 1
If (P div i > i) Then
// 这个判断语句的作用是为了防止当 P 为平方数时
// 若(P div i >= i)则会将 sqrt(P) 重复加入约数中
p_divisors[p_count] = P div i
p_count = p_count + 1
End If
End If
End For
// 用这种方法得到的约数序列需要进行排序
Sort(p_divisors)
在得到p_divisors
和q_divisors
之后,再通过双重循环,即可将所有的数字对打印出来:
For i = 0 .. p_count - 1
For j = 0 .. q_count - 1
Output(p_divisors[i] + ' ' + q_divisors[j])
End For
End For
到此,本题也就顺理解决。
1 #include <iostream> 2 #include <cmath> 3 #include <cstdio> 4 #include <algorithm> 5 using namespace std; 6 7 8 int p_divisors[5005]; 9 int q_divisors[5005]; 10 11 int main(){ 12 int i, j, p, q, p_count = 0, q_count = 0; 13 scanf("%d %d", &p, &q); 14 15 for(i = 1; i <= p; i++){ 16 if(p % i == 0){ 17 p_divisors[p_count] = i; 18 p_count++; 19 } 20 } 21 22 for(i = 1; i <= q; i++){ 23 if(q % i == 0){ 24 q_divisors[q_count] = i; 25 q_count++; 26 } 27 } 28 /* 29 for(int i = 1; i <= sqrt(p); i++){ 30 if(p % i == 0){ 31 p_divisors[p_count] = i; 32 p_count++; 33 if(p / i > i){ 34 p_divisors[p_count] = p / i; 35 p_count++; 36 } 37 } 38 } 39 sort(p_divisors, p_divisors + p_count); 40 41 for(int i = 1; i <= sqrt(q); i++){ 42 if(q % i == 0){ 43 q_divisors[q_count] = i; 44 q_count++; 45 if(q / i > i){ 46 q_divisors[q_count] = q / i; 47 q_count++; 48 } 49 } 50 } 51 sort(q_divisors, q_divisors + q_count);*/ 52 53 54 55 for(i = 0; i < p_count; i++){ 56 for(j = 0; j < q_count; j++){ 57 printf("%d %d ", p_divisors[i], q_divisors[j]); 58 } 59 } 60 61 return 0; 62 63 }