0

I want to add prime numbers under two million, and for some reason it keeps running with no output. After some testing I know that the error itself is in the the addprimes function however from what I understand the program should return an output.

static ArrayList<Integer> primes = new ArrayList<Integer>();

public static void findPrimes(int limit)
{
    primes.add(2);
    int Number = 3;
    int n = 0;
    boolean add = true;

    if(Number % 2 != 0)
        primes.add(Number);

    for(int i = Number; i<limit; i+=2)
    {
        n = 2;
        add = true;


        while(n < i)
        {
            if(i % n == 0)
            {
                add = false;
                continue;
            }
            n++;
        }


        if(add == true)
            primes.add(i);

    }
}


public static int addPrimes()
{
    int Total = 0;
    int temp = 0;
    for(int i = 0; i < primes.size(); i++)
    {
        temp = primes.get(i);
        Total += temp;
    }
    return Total;

}
}
Rahul Sharma
  • 2,867
  • 2
  • 27
  • 40
Rpmp
  • 17
  • 6

2 Answers2

0

You call continue without increment the value of n.

Try updating while loop to the following:

while(n < i)
{
   if(i % n == 0)
   {
       add = false;
       n++;
       continue;
   }
   else
       n++;
}

Check the answers of this question for more information about continue.

Update

In case your code ended up with too big numbers, then you have to use another data-types like Long, Double ..etc.

Community
  • 1
  • 1
Kh.Taheri
  • 946
  • 1
  • 10
  • 25
  • Thanks now it works for int, however if the number is too big then like the problem asks, then it does not but I think I know how to fix this issue. – Rpmp Feb 02 '17 at 02:32
  • Good luck, but if you found my answer helpful; you could check it as a Correct Answer ;) – Kh.Taheri Feb 02 '17 at 02:33
0
  1. You can just comment out continue to come out of infinite loop.
  2. I can see that value 3 is repeating in the prime number list for that you can comment out these lines

    
    //    if(Number % 2 != 0) 
    //          primes.add(Number);
    
Kiran Bhagwat
  • 574
  • 1
  • 6
  • 13