欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

cleancode(3)

程序员文章站 2022-03-15 19:33:19
...
#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;
}

相关标签: 算法的乐趣