Click here to Skip to main content
15,888,208 members
Please Sign up or sign in to vote.
3.00/5 (3 votes)
See more:
Greetings :)

I'm trying to write a code to calculate the sum of prime numbers between 200,000 and 400,000.

but when I run it, it gives me 0 as a result! debugged it and seems the problem is with the "%" operator! can anyone tell me what's wrong please? (functions below - I split the code too much to help debug, sorry about that).

C#
private string SolveProblem2()
{
	double loopEnd = 200000, numCurrent = 200000;
	BigInteger sum = new BigInteger("0");

	for (int i = 0; i < loopEnd ; i++, numCurrent++)
	{
		SolveProblem2_1(numCurrent, ref sum);
	}

	return sum.ToString(); //returns final result

}


private void SolveProblem2_1(double numCurrent, ref BigInteger sum)
{
	int j = 2;
	double res = 0;

	while (j < numCurrent)
	{
		res = numCurrent % j;
		if (res == 1)
		{
			j++;
		}
		else
		{
			break;
		}
	}

	if (j == numCurrent)
	{
		sum = sum.add(new BigInteger(numCurrent.ToString()));
	}

}


Note that I used 200,003 for testing since its a Prime number (given by a friend's another code), but according to my code it can be divided by 3 with a remainder other than one!
Posted
Updated 4-Sep-12 10:19am
v2
Comments
[no name] 4-Sep-12 16:02pm    
"divided by 3 without any remainder", how did you come to that conclusion? When j = 3 res = 2 which is correct.
NiZaR.TecH 4-Sep-12 16:19pm    
lol I'm sorry I meant with a remainder other than 1!
[no name] 4-Sep-12 16:33pm    
Sorry, my bad, Did not scroll down far enough. Curse of getting old.

1 solution

Shouldnt this be

C#
if (numCurrent % j== 0)
instead?

If you take 10 % 3 the reminder would be 1.. See examples here (I know its VB but examples still valid :) ):
http://msdn.microsoft.com/en-us/library/se0w9esz%28v=vs.110%29.aspx[^]
 
Share this answer
 
v2
Comments
NiZaR.TecH 4-Sep-12 16:15pm    
Thanks for your reply, but I still get the same final result and results in debugging. :(
Kenneth Haugland 4-Sep-12 16:19pm    
I think the mod function is not your only mistake. Here was myt take on prime numbers:
http://www.codeproject.com/Articles/429694/Finding-prime-numbers
and here is an example in C# using the aggregate function to calculate the sum of all the primes:
http://www.geekality.net/2009/10/19/the-sieve-of-atkin-in-c/
There should be enough information for you there :)
NiZaR.TecH 4-Sep-12 16:32pm    
Thanks for the links, I think I solved it with your help! but instead of:
if ( numCurrent & j == 0 )
I put:
if ( numCurrent & j != 0 )

and its working :) :) thanks a million :)
Kenneth Haugland 4-Sep-12 16:35pm    
Good :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900