我对hackerrank有一个问题,如下所示。我的答案是在这个问题描述之后,它在运行代码之后显示ok,但是当我提交代码时,这个代码只通过了6个测试用例中的3个。我还是不知道我的错误在哪里。任何帮助都将不胜感激。谢谢。
考虑两组正整数,A={a0,a1,.,a(n-1)}和B={b0,b1,…,b(m-1)}。我们说,如果满足下列条件,则正整数x在集合A和B之间: A中的所有元素都是x的因子,x是B中所有元素的因子,给定A和B,找出并打印出两个集合之间的整数数(即可能的s)。 输入格式 第一行包含两个空格分隔的整数,分别描述n(集合A中的元素数)和m(集合B中的元素数)的值。第二行包含不同的空格分隔整数,描述a0,a1,.,a(n-1).第三行包含描述b0,b1,.,b(m-1)的不同的空格分隔整数. 约束条件 1<= n,m <= 10 1<= a(i) <= 100 1<= b(i) <= 100 输出格式 打印被认为介于A和B之间的整数数。 样本输入 2 3 2 4 16 32 96 样本输出 3. 解释 A={2,4}和B={16、32、96}之间的整数为4、8和16。
我的代码:
public class Solution {
public static boolean checkX_function(int Ax, int [] b){
for(int i=0; i<b.length; i++){
if(b[i]%Ax!=0){
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(); // n: length of array A
int m = in.nextInt(); // m: length of array B
int[] a = new int[n];
for(int a_i=0; a_i < n; a_i++){
a[a_i] = in.nextInt();
}
int[] b = new int[m];
for(int b_i=0; b_i < m; b_i++){
b[b_i] = in.nextInt();
}
boolean checkX = false;
int count=0;
for(int i=0; i<n; i++){
for(int j=i; j<n; j++){
int Ax = 0;
Ax = a[i]*a[j];
//check if Ax is satisfied for all elements in B
checkX = checkX_function(Ax, b);
if (checkX == true){
count++;
}
}
}
System.out.println(count);
}
}发布于 2017-05-08 12:32:35
请看一看
int main(){
int n;
int m;
int currentNum,count=0 ;
cin >> n >> m;
vector<int> a(n);
for(int a_i = 0;a_i < n;a_i++){
cin >> a[a_i];
}
vector<int> b(m);
for(int b_i = 0;b_i < m;b_i++){
cin >> b[b_i];
}
currentNum = a[n-1];
do{
bool check1 = true;
for(int i=0;i<n;i++){
if(currentNum%a[i]!=0){
check1 = false;
}
}
if(check1){
bool check = true;
for(int i=0;i<m;i++){
if(b[i]%currentNum!=0){
check = false;
}
}
if(check){
// cout<<currentNum<<"\n";
count++;
}
}
currentNum ++;
}while(currentNum <=b[0]);
cout<<count;
return 0;
}发布于 2019-07-30 05:49:07
嗨,我写了下面的代码,它通过了所有的测试用例。
function getTotalX(a, b) {
// Write your code here
let counter = 0;
for (let currentNum = 0; currentNum <= 100; currentNum++) {
let check1 = true;
for (let j = 0; j < a.length; j++) {
if (currentNum % a[j] != 0) {
check1 = false;
}
}
if (check1) {
let checkx = checkFactor(currentNum, b);
if (checkx) {
counter++;
}
}
}
return counter;
}
function checkFactor(ax, b) {
for (let i = 0; i < b.length; i++) {
if (b[i] % ax != 0) {
return false;
}
}
return true;
}
发布于 2022-09-14 22:07:25
def getTotalX(a, b):
def factor(x,y):
return x%y==0
list1=[]
for i in range(max(a),min(b)+1):
if all(factor(i,x) for x in a) and all(factor(x,i) for x in b):
list1.append(i)
return len(list1)https://stackoverflow.com/questions/40372031
复制相似问题