-3
// finding sum of all primes under 2 million
public class lll {

    public static void main(String[] args) {
        int a = 2;
        int b = 0;
        int c = 0;
        while (a < 2000000) {
            int i = 1;
            for (i = 1; i * i <= a; i++) {
                if (a % i == 0)
                //if factor is found of number a b goes up 1
                {
                    b++;
                }
            }
            // all primes have only one factor <= sqrt   (1)
            if (b == 1)
            // if b =1 , a is prime so c+=a
            {
                c += a;
            }
            //reset b and add one to a to move on 
            b = 0;
            a++;
            // for error checking see description 
            System.out.println(c);

        }
        System.out.println(c);
    }
}

Im trying to make a code to find the sum of all primes under 2 million, heres what i have it gives 1179908154, but this is not right, c is supposed to be the sum. I tried getting c after every check of number being prime and it shows that during the running of this code it lips from positive to negative and then back again. it makes no sense a starts at 1, a goes up c starts at 0, it goes up by a so how is c getting negative (a is never negative), please help me, I have managed to used this method of prime checking to correctly get the 10001st prime, it worked then.

bowmore
  • 10,842
  • 1
  • 35
  • 43
Iexist
  • 53
  • 1
  • 7

3 Answers3

1

A 32 bit integer can only hold numbers below about 2 billion. If you try to add more to that number (accessible by Integer.MAX_VALUE), you will end up "flipping" to negative numbers. Try out the following code:

    System.out.println(Integer.MAX_VALUE);
    System.out.println(Integer.MAX_VALUE + 1);
    System.out.println(Integer.MIN_VALUE);

So your problem is that integers aren't big enough! How can you solve this? The simplest way is to use a long instead of an int. Hypothetically, what if a long isn't even big enough? Then you can use a class like BigInteger, which isn't constrained to a fixed number of bits, and can grow as necessary.

user548928
  • 46
  • 4
0

Well, you declared c as an int which in java has a max value of 2,147,483,647 . The sum of all primes less than 1 million is 37,550,402,023, so Im thinking you are surpassing the data storage for int which is why its flipping negative on you.

CodeNoob
  • 250
  • 3
  • 9
0

My guess is that it has something to do with memory. In java the maximum number an integer can hold is 2147483647. So if the sum of primes goes over this number, it will loop back to -2147483648 and continue counting. Try making your variable c a long instead.

user3817808
  • 187
  • 1
  • 10