java - 求小于指定数的任意数的倍数之和。我的错误在哪里?
问题描述
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;
}
}
我自己编写了这段代码。看起来一切都很好,但我没有得到所需的输出。为什么会这样?
解决方案
看起来你的数学有点不对劲。试着把它分成更小的部分,以确认你得到了你所期望的。返回 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;
}
如果你以同样的方式拆分你的方法,你会看到你稍微错过了标记的地方。
推荐阅读
- java - centos 6.10编译openjdk8时出错
- javascript - 如何通过 wordpress rest api 从自定义表中获取所有记录?
- css - 单词中 1 个字符的 CSS
- docker - 即使 UFW 拒绝访问,Docker 端口也会在界面上可见
- git - git忽略了一些不应该被忽略的东西
- django - get_expiry_age() 在 Django 中返回什么
- javascript - 将登录用户信息传递给 javascript 的问题
- excel - VBA - 使用 VBA 代码时未导出 XML 映射
- java - 如何将图片发送到 Discord 频道
- r - 具有滞后变量的 dplyr rowwise