cleancode(3)

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Prime{
public:
	Prime(){}
	Prime(int maxSize) {
		checkPrimeMaxRange(maxSize);
		for (int i = 0; i <= maxSize; ++i) {
			primeTable.push_back(true);
		}
		getRightPrimeTable();
	}
	~Prime(){}

	void checkPrimeMaxRange(int maxSize) {
		if(maxSize < 2){
			cout << "size should bigger than one." << endl;
		}
		else {
			primeMaxRange = maxSize;
		}
	}

	void getRightPrimeTable() {
		for (int i = 2; i <= primeMaxRange; ++i)
		{
			if (primeTable[i])
			{
				for (int j = i * i; j <= primeMaxRange; j += i)
					primeTable[j] = false;
			}
		}
	}

	void showAllPrimes() {
		for (int i = 2,count=5; i < primeMaxRange; ++i) {
			if (primeTable[i]) {//分裂到不能再分出小函数
				printf_s("%5d", i);
				count--;//保证并列的语句处于同一个逻辑层
				if (isNextLine(count)) cout << endl;
			}
		}
		cout << endl;
	}
	bool isNextLine(int &count) {
		bool ans = false;
		if (count == 0){
			count = 5;
			ans = true;
		}
		return ans;
	}
	
private:
	int primeMaxRange;
	vector<bool> primeTable;
};

int main()
{
	Prime test(233);
	test.showAllPrimes();
	system("pause");
	return 0;
}

发布了27 篇原创文章 · 获赞 1 · 访问量 1424

猜你喜欢

转载自blog.csdn.net/qq_34890856/article/details/103995370
3
3-3
今日推荐