版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
Problem Description
对于我们来说求两个数的LCM(最小公倍数)是很容易的事,现在我遇到了一个问题需要大家帮助我来解决这问题,问题是:给你一个数n,然后统计有多少对(a<=b) LCM(a,b)=n;例如LCM(a,b)=12; 即(1,12),(2,12),(3,12),(4,12),(6,12),(12,12),(3,4),(4,6);
Input
输入数组有多组,每组数据包含一个整数n(n<=10^9);
Output
输出每组数据的对数。
Sample Input
2
3
4
6
Sample Output
2
2
3
5
Hint
Source
fmh
思路:
题目给的数据范围较大,采用long类型。
首先找出n的因子,入栈
然后在栈的数据中找到符合题目条件的数
package hello;
import java.util.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long[] num = new long[111000];
while(sc.hasNext()) {
int count = 0;
int top = 0;
long n = sc.nextLong();
for (int i = 1; i*i <= n; i++) { // 找到n的因子,入栈
if (n % i == 0) {
num[top++] = i;
if (i*i != n) {
num[top++] = n/i; // n/i也是n的因子
}
}
}
for (int i = 0; i < top; i++) { // 遍历栈,找到最小公倍数为n的
for (int j = i; j < top; j++) {
if (Lcm(num[i], num[j]) == n) {
count++;
}
}
}
System.out.println(count);
}
}
public static long Lcm(long a, long b) { // 求最小公倍数
if (a < b) {
long t = a;
a = b;
b = t;
}
long mul = a * b;
while (b > 0) {
long r = a % b;
a = b;
b = r;
}
return mul/a;
}
}