isPrime fun

can anyone tell me what's wrong with this fun!!
it doesn't work with big numbers !
1
2
3
4
5
6
7
bool isPrime(long n, long count) {
		if (count >= n)
			return true;
		if (n % count == 0)
			return false;
		return isPrime(n, count+1);
	}
Show the call of the function with "big numbers".
1
2
3
4
5
long sum = 0;
		for (long i = 2; i < 2000000; i++){
			if(isPrime(i,  2))
				sum += i;
		}
it shows that error(in java)
java.lang.StackOverflowError
I think that the problem is that the function is recursive and the stack can not accommodate 2000000 - 1 calls of the function.
Last edited on
So.. is there any other function that do the isPrime efficiently ..?
Simply rewrite it using a loop. Take also into account that it is enough to check divisors that less than or equal to sqrt( n )
Last edited on
i do! .. this one
1
2
3
4
5
6
7
8
9
 bool isPrime(long n){
		for(int i = 2; i < n; i++){
			if (i == n)
				continue;
			if (n % i == 0)
				return false;
		}
		return true;
	}

but it never ends!!!
If you need the answer then the sum is equal to 142913828922
thanks vlad ,, but i need the function :)



1
2
3
4
5
6
7
8
bool isPrime( long n )
{
	for( long i = 2; i * i  <= n; i++ )
	{
		if ( n % i == 0 ) return false;
	}
	return true;
}
Last edited on
it works! ,, thank you @vlad :))
I compared the result gotten by executing this function and the result of my function and they coinsided.

142913828922
142913828922
it gives me this 143042032116
however, yours is the wright one.
Check the statement

for( long i = 2; i * i <= n; i++ )
shouldn't it to be i < n , not = !!?
coz if it checks 2%2 == 0 , then it's nor prime!
I wrote the function. Can you yourself understand how it works?
Last edited on
oh .. it's squrt n . .ok got it
Topic archived. No new replies allowed.