我試圖找到兩個給定數字之間的所有素數並將總數加起來。查找兩個數字之間的素數
我有這個循環,正確的質數檢測。
但是,由於某種原因,我不知道如何總結所有素數。
int a,b,i,j,sum=0;
do
{ cout << "Enter a number: ";
cin >> a;
if (a < 4 || a > 1000000)
{ cout << "Input must be between 4 and 1000000 inclusive." << endl;
}
}while (a < 4 || a > 1000000);
do
{ cout << "Enter a second number: ";
cin >> b;
if (b < 4 || b > 1000000)
{ cout << "Input must be between 4 and 1000000 inclusive." << endl;
}
}while (b < 4 || b > 1000000);
if (a > b)
{ int hold;
hold = b;
b = a;
a = hold;
}
cout << "The prime numbers between " << a << " and " << b << " inclusive are: " << endl;
//int sum;
for (i = a; i <= b; i++)
{
for (j = 2; j <= i; j++) // Changed the < to <=, and got rid of semicolon
{
if (!(i%j)&&(i!=j)) break;
if (j==i)
{
cout << i << endl;
sum += i;
cout << sum ;
}
}
}
變量sum
給我垃圾的結果。
修復您的格式和使用明智的變量名稱,謝謝你... – ScarletAmaranth
你初始化它('sum')爲零嗎?範圍是多少? 'sum'的類型是什麼?您也可能遇到溢出,具體取決於範圍。 – amit
我是那麼做的 int sum = 0; – Mahmoud