【发布时间】:2018-05-15 14:52:54
【问题描述】:
我正在尝试一个 codility 任务,遇到了一个问题,给定两个非空数组 A 和 B 的 Z 整数,返回位置 K 的数量 A[K] 和 B[K ] 完全相同。
例如,给定:
A[0] = 15 B[0] = 75
A[1] = 10 B[1] = 30
A[2] = 3 B[2] = 5
该函数应返回 1,因为只有一对 (15, 75) 具有相同的素数除数集。
例如,给定:
N = 15 and M = 75, the prime divisors are the same: {3, 5};
N = 10 and M = 30, the prime divisors aren't the same: {2, 5} is not equal to {2, 3, 5};
N = 9 and M = 5, the prime divisors aren't the same: {3} is not equal to {5}.
我应用的解决方案如下,通过尝试多个测试用例我没有发现错误的答案,但在代码中它说答案不正确。 请帮我找出原因:
public class CommonPrimeDivisors {
public static void main(String[] args) {
int A[] = new int[] { 175 };
int B[] = new int[] { 350 };
System.out.println(new CommonPrimeDivisors().solution(A, B));
}
public int solution(int A[], int B[]) {
int counter = 0;
for (int i = 0; i < A.length; i++) {
double max = Math.max(A[i], B[i]);
double min = Math.min(A[i], B[i]);
double remainder = (double) max / min;
if(remainder==(int)Math.ceil(remainder)){
if (min % remainder == 0) {
counter++;
}
}
}
return counter;
}
}
【问题讨论】:
-
System.out.println(factors);factors是什么? -
对不起。不幸的是,它被留在了那里。
-
如果您想查看 A divides B 是否可以被 A 整除,您只需检查 B % A == 0,其中 A 和B 是整数。
标签: java arrays primes prime-factoring