两个整数除数和

问题描述

我写了这段代码,但结果我得到了错误的答案,我不知道为什么。 我必须得到 3 个整数 a,b,x 。然后找到 a,b 除数,如果除数的总和不超过 x,则为 res++,最后打印 res。

import java.util.Scanner;

public class testQuestion {
    public static void main(String[] args) {
        Scanner input = new Scanner(system.in);
        int a = input.nextInt();
        int b = input.nextInt();
        int x = input.nextInt();
        int[] resB = new int[b];
        int[] resA = new int[a];
        int res = 0;

        for (int i = 1; i <= a; i++) {
            if (a % i == 0)
                resA[i - 1] += i;
            if (b % i == 0)
                resB[i - 1] += i;
        }
        for (int i : resA) {
            if (i > 0)
                for (int j : resB) {
                    if (i + j <= x && j > 0) {
                        res++;
                    }
                }
        }
        System.out.println(res);
    }
}

解决方法

不确定这是否有帮助,似乎您有 2 个存储空间,A 和 B。通过循环 A,您可能会错过 B。示例 B 有 10 条记录,A 只有 1 条记录,而 A等于或小于 0 则不会循环。为确保这一点,循环 A 和 B 并检查它是否 >0。

-但是如果 A 为空,则不会循环 B。

    for (int i : resA) {
        for (int j : resB) {
           if(j > 0 && i > 0) {
             if (i + j <= x) {
                    res++;
             }
           }
        }
    }

更新

首先:通过删除 resB 来创建一个变量。离开 int[] resA = new int[a];

其次:循环A并加入resA

第三:循环B并检查除法。然后比较任何 B 与任何 A 的总和是否 > x。

第四:如果你想检查一个空的A应该让B加0,你可能会做出调整。或者,你可能根本不计算它。取决于你需要什么。如果为空,可能会对 B 执行相同的操作。