问题描述
问候:)
我正在尝试编写代码来计算200,000到400,000之间的素数之和.
但是当我运行它时,结果是0!调试它,似乎问题出在%"运算符!谁能告诉我怎么了? (下面的功能-我对代码进行了过多拆分以帮助调试,对此感到抱歉).
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).
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()));
}
}
请注意,由于它是素数(由朋友的另一个代码提供),因此我使用了200003进行测试,但是根据我的代码,它可以被3除以除一个以外的余数!
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!
推荐答案
if (numCurrent % j== 0)
?
如果您选择10%3,则提醒将为1..请参见此处的示例(我知道它的VB,但示例仍然有效:)):
http://msdn.microsoft.com/en-us/library/se0w9esz%28v = vs.110%29.aspx [ ^ ]
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[^]
这篇关于C#模数运算符(%)无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!