-1

I think I'm using the Eratosthenes sieve, since an array can't take long values as indexes, I get the memory error even when I use casting. Should I rather create a Map or List containing long values and compute that way ? This is the code: **

int max = 2000000;
    int sum = 0;
    boolean[] list = new boolean[max];

    list[0] = false;
    list[1] = false;
    for (int i = 2; i < max; i++) {
      list[i] = true;
    }

    for (int i = 2; i < max; i++) {
      for (int j = 1; j < max; j++) {      
        if(list[j]&&i*j<max){        
          list[i*j] = false;
        }
      }
      if(list[i]){
      sum+=i;     
      }
    }
    System.out.println(sum);

**

  • Where exactly are you hitting the memory error? – aksappy Dec 05 '19 at 17:28
  • The range for the int type is `-2^32` to `+2^32`. How come you are getting OOM already? Are you sure it's not a Java heap size error? Can you post your error log? – Taslim Oseni Dec 05 '19 at 17:31
  • java.lang.ArrayIndexOutOfBoundsException: length=2000000; index=-2147464558 – user11530714 Dec 05 '19 at 17:33
  • at java.lang.reflect.Method.invoke(Native Method) at com.duy.android.compiler.java.Java.run(Java.java:115) at com.duy.ide.javaide.run.activities.ExecuteActivity.executeDex(ExecuteActivity.java:147) at com.duy.ide.javaide.run.activities.ExecuteActivity.exec(ExecuteActivity.java:124) at com.duy.ide.javaide.run.activities.ExecuteActivity.access$100(ExecuteActivity.java:45) at com.duy.ide.javaide.run.activities.ExecuteActivity$1.run(ExecuteActivity.java:88) at java.lang.Thread.run(Thread.java:764) – user11530714 Dec 05 '19 at 17:34

1 Answers1

0

Your problem is that the expression i*j is overflowing the int type.

You can try casting each to a long before multiplying.

E.g.,

public class HelloWorld{

 public static void main(String []args){
    int i = 200000;
    int j = 20000;
    System.out.println("i*j = " + (i*j));
    System.out.println("(long) i*(long j) = " + ((long) i*(long) j));
 }

}

$javac HelloWorld.java
$java -Xmx128M -Xms16M HelloWorld
i*j = -294967296
(long) i*(long j) = 4000000000
Matthew McPeak
  • 17,705
  • 2
  • 27
  • 59