读取两数之间的质数并统计个数(默认0—100)

//类声明
#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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值