首页 > 解决方案 > 求小于指定数的任意数的倍数之和。我的错误在哪里?

问题描述

这是我的另一个解决方案,其中输出按预期显示

 public class Logic2 {
        public static void main(String[] args) {
            long sum = 0;
            calculation key = new calculation();
            sum = key.sum(3, 1000);
            System.out.print(sum);
        }
   }

class calculation {
    long total = 0;
    public long sum(int num, int limit) { //multples of num less than limit
        int number = Integer.valueOf(limit / num);
        if (limit % num == 0) {
            number -= 1;
        }

        total = (number / 2) * (2 * num + (number - 1) * num);
        return total;
    }
}

我自己编写了这段代码。看起来一切都很好,但我没有得到所需的输出。为什么会这样?

标签: javaalgorithm

解决方案


看起来你的数学有点不对劲。试着把它分成更小的部分,以确认你得到了你所期望的。返回 166833 的工作示例

public static void main(String[] args) {
    int a = 3, N = 1000;
    System.out.println("Sum of multiples of " + a +
            " up to " + N + " = " +
            calculate_sum(a, N));

}

private static int calculate_sum(int a, int N) {
    // Number of multiples
    int m = N / a;

    // sum of first m natural numbers
    int sum = m * (m + 1) / 2;

    // sum of multiples
    return a * sum;
}

如果你以同样的方式拆分你的方法,你会看到你稍微错过了标记的地方。


推荐阅读