百练 / 2017计算机学科夏令营上机考试: A (判决素数个数)

A:判决素数个数

描述

输入两个整数X和Y,输出两者之间的素数个数(包括X和Y)。

输入
两个整数X和Y(1 <= X,Y <= 10 5)。
输出
输出一个整数,表示X,Y之间的素数个数(包括X和Y)。
样例输入
1 100
样例输出
25
#include<iostream>
#include<math.h>  
using namespace std;

bool test(int x)
{
	int j = 2;
	if (x <= 1) {return false;}
	if (x == 2 || x == 3) { return true; }
	for (j = 2; j <= ((int)sqrt(x)); j++)
	{
		if (x%j == 0)
		{
			return false;
		}
	}
	return true;
}

int main()
{
	int ans=0;
	int a, b;
	cin >> a >> b;
	if (a > b) { int c = a; a = b; b = c; }
	for (int i = a; i <= b; i++)
	{
		if (test(i)) { ans++; }
	}
	cout << ans;
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36718092/article/details/80209824