解题思路:
暴力
优化前(代码没有错,但会超时):
import java.util.*;
public class Main {
public static void main(String[] args) {
long n = 2021041820210418L;
long cnt = 0;
for (long a = 1; a <= n; a++) {
for (long b = 1; b <= n; b++) {
for (long c = 1; c <= n; c++) {
if (a * b * c == n) cnt++;
}
}
}
System.out.print(cnt);
}
}
优化后(先求出目标数字的所有分解因子,再根据这些分解因子暴力求解):
注意:
list.size()方法返回的是int类型,所以在for循环语句上作为条件比较时,如果不强制转型,
那么a,b,c都要是int类型
import java.util.*;
public class Main {
public static void main(String[] args) {
long n = 2021041820210418L;
long cnt = 0;
List<Long> list = new ArrayList<>();
for (long i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
list.add(i);
list.add(n / i);
}
}
for (int a = 0; a < list.size(); a++) {
for (int b = 0; b < list.size(); b++) {
for (int c = 0; c < list.size(); c++) {
if (list.get(a) * list.get(b) * list.get(c) == n)
cnt++;
}
}
}
System.out.print(cnt);
}
}