简体   繁体   English

Java - 添加所有奇数奇怪的行为

[英]Java - Add all odd numbers strange behaviour

I am doing a maths challenge for project euler and i have come across a strange problem when running the program.我正在为欧拉项目做一个数学挑战,我在运行程序时遇到了一个奇怪的问题。 The result should be the sum of all the odd numbers up to 10,000,000 but i get a negative number, what am i doing wrong?结果应该是所有不超过 10,000,000 的奇数之和,但我得到一个负数,我做错了什么?

package program;

import java.util.*;

public class MainClass {

/**
 * @param args
 */
public static void main(String[] args) {

    int total = 0;

    for (int counter = 1; counter < 10000000; counter++) {
        if (!((counter % 2) == 0)) {
            total+=counter;
        }

    }
    System.out.println(total);

}

} }

Use a long instead of an int .使用long而不是int You're getting a negative number due to integer overflow.由于 integer 溢出,您得到一个负数。

The int variable can't hold the total because the total is too big. int变量不能保存总数,因为总数太大了。 At some point in the loop, you're getting an integer overflow and it's "rolling over" to a negative number:在循环中的某个时刻,您会遇到integer 溢出并且它“滚动”到负数:

You need a long .你需要一个long的。

A matter of style and efficiency, I'd change the code to iterate by 2 so that you don't need the test for oddness:出于风格和效率的考虑,我将代码更改为以2为单位进行迭代,这样您就不需要进行奇数测试:

public static void main(String[] args) {
    long total = 0;
    for (int counter = 1; counter < 10000000; counter += 2) { // iterate by 2
        total += counter;
    }
    System.out.println(total);
}

You should use long total = 0;你应该使用long total = 0; instead of int total = 0;而不是int total = 0; int in java is 4 bytes and ranges from -2,147,483,648 to 2,147,483,647. java中的int4字节,取值范围为-2,147,483,648~2,147,483,647。

so 2,147,483,647 + 1 = -2,147,483,648所以2,147,483,647 + 1 = -2,147,483,648

The total for this loop comes out to be 25,000,000,000,000 which can be accommodated by long此循环的total为 25,000,000,000,000,可由long容纳

Just to throw in the more clever solution to this problem (MATH. yay).只是为了解决这个问题(MATH.yay)提供更聪明的解决方案。

You can solve this much easier, you just need to know that the sum of odd numbers from 1..2n-1 is equal to the square of n.你可以更容易地解决这个问题,你只需要知道 1..2n-1 的奇数之和等于 n 的平方。 It's pretty easy to prove this with induction for those who want to try.对于那些想尝试的人来说,通过归纳法很容易证明这一点。

Anyways this means that the sum from 1..X is equal to: ((X + 1) / 2)**2无论如何,这意味着 1..X 的总和等于: ((X + 1) / 2)**2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM