//类声明
#ifndef FUNCTION_H_
#define FUNCTION_H_
class Prime
{
public:
Prime();
~Prime();
private:
int nCount; //存放质数的个数
public:
void Search(int nStart = 0, int nEnd = 100); //搜索函数,默认值为0-100
};
#endif
//类定义
#include <iostream>
#include "function.h"
void Prime::Search(int nStart, int nEnd)
{
using namespace std;
cout.setf(ios::left); //设置输出左对齐,全局有效
cout << "输出"<<nStart<<" - "<<nEnd<<"内所有质数:" << endl;
if (nStart <= 2)
nStart = 2;
for (int a = nStart; a <= nEnd; a++)
{
int nYue = 0;
for (int i = 1; i <= a; i++) //计算每个数的约数
{
if (a % i == 0)
nYue++;
}
if (nYue == 2) //如果只有两个约数,即质数
{
cout.width(5); //设置输出宽度为5
cout << a << " ";
nCount++;
if (nCount % 4 == 0) //每输出4个换行
cout << endl;
}
}
cout << endl << "Total: " << nCount << endl;
}
Prime::Prime()
{
nCount = 0;
}
Prime::~Prime()
{
}
//主函数
// file.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include "function.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int nStart, nEnd;
cout << "找质数!" << endl;
do{
cout << "起始数须小于结束数,结束数须大于2!"<<endl;
cout << "输入起始数:";
cin >> nStart;
cout << "输入结束数:";
cin >> nEnd;
} while (nStart >= nEnd || nEnd <= 2);
Prime m_prim;
m_prim.Search(nStart, nEnd);
system("pause");
return 0;
}