Stack overflow error in Java recursion -


i'm trying implement code returns sum of prime numbers under 2 million. have isprime(int x) method returns true if the number prime. here is:

public static boolean isprime(int x) {          (int = 2; < x; i++) {              if (x % == 0) {                 return false;             }          }         return true;      } 

and other method, i'm trying implement recursively, works until number, on number , stack overflow error. highest got code work 10,000.

here is:

public static int sumofprimes(int a) {      if (a < 2000000) {  //this limit          if (isprime(a)) {             return + sumofprimes(a + 1);          } else {             return sumofprimes(a + 1);         }      }     return -1; } 

so why stack overflow error when number gets bigger , how can deal this? also, how deal writing code such big numbers? ie: normal number operations larger numbers? wrote recursively because thought more efficient still wont work.

your isprime function inefficient, doesn't have go x, it's enough go square root of x.

but not reason why solution doesn't work. cannot have recursion depth of 1 million.

i solve problem iteratively, using sieve of eratosthenes , loop on resulting boolean array.


Comments

Popular posts from this blog

mysql - FireDac error 314 - but DLLs are in program directory -

git - How to list all releases of public repository with GitHub API V3 -

c++ - Getting C2512 "no default constructor" for `ClassA` error on the first parentheses of constructor for `ClassB`? -