(4)設計一個可以找出整數1至N之間的質數,整數N之值由使用者輸入,找到的質數請輸出至螢幕上
將上述C++語言的程式修改成C++物件導向的程式
是將題目以class物件方式寫出程式。
2006-12-20 17:25:08 · 1 個解答 · 發問者 ㄚ鵬 1 in 電腦與網際網路 ➔ 程式設計
#include
#include
#include
using namespace std;
class Prime
{ public: Prime(int n);
~Prime();
void find();
void print();
private: int n,
*p,
s; // Square root of n
};
Prime:: Prime(int n)
{ s = sqrt((float) n);
p = new int[n+1];
for (this->n=3; this->n<=n; this->n++)
p[this->n] = 1;
p[1] = p[2] = 1;
this->n = n;
}
Prime::~Prime()
{ delete p;
}
void Prime::find()
{ int i, i2, j;
for (i=3; i<=s; i+=2)
if (p[i])
for (i2=i<<1, j=i+i2; j<=n; j+=i2)
p[j] = 0;
}
void Prime::print()
{ int i, t;
const int w = 6;
cout << setw(w) << '2';
for (t=1, i=3; i<=n; i+=2)
if (p[i])
{ cout << setw(w) << i;
t++;
if (t==80/w)
{ t = 0;
cout << '\n';
} } }
int main(int argc, char **argv)
{ int n;
cout << "Please enter an integer larger than 4: ";
cin >> n;
if (n < 4) n = 9;
Prime p(n);
p.find();
p.print();
system("PAUSE");
return 0;
}
2006-12-20 20:01:04 · answer #1 · answered by ? 7 · 0⤊ 0⤋