This is my another solution where the output is shown as expected
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;
}
}
我自己编写了这段代码。似乎一切正常,但我没有得到所需的输出。为什么会这样?
答案 0 :(得分:0)
您的数学似乎有点错误。尝试将其分解成较小的部分,以确保您得到了期望的结果。一个返回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;
}
如果以同样的方式拆分方法,您将看到略微遗漏标记的位置。
答案 1 :(得分:0)
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*num+(number-1)*num))/2;
//previouslly total = (number / 2) * (2 * num + (number - 1) * num);
return total;
}
}
我自己发现了这个错误。在那,总计,如果我们写(number / 2),那么它将给出整数值,因此我没有得到所需的输出。无论如何,感谢大家在列表中查看我的帖子,对此我表示感谢。 :)