java我能用一个循环优化这个函数吗(在第一种方法中)?
我想知道是否有一种方法可以通过循环(在方法findPairs中)来优化这个问题,该循环打印出整数对,这样从1到N的数字和这对数字的和小于50,并且有3个以上的公约数
public class foo {
static void findPairs(int N) {
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
if (commDiv(i, j) > 3 && i + j < 50)
System.out.println(i + " , " + j);
}
}
}
static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static int commDiv(int a, int b) {
int n = gcd(a, b);
int result = 0;
for (int i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
if (n / i == i)
result += 1;
else
result += 2;
}
}
return result;
}
}
共 (0) 个答案