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
Post a Comment