poj 3978 primes

本文介绍了一种通过编程计算两个整数间质数数量的方法。使用C++实现了一个质数判断函数,并预先标记了所有非质数,之后计算指定区间内的质数数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
Primes
Time Limit: 1000MS  Memory Limit: 65536K 
Total Submissions: 2975  Accepted: 1144 

Description

A pretty straight forward task, calculate the number of primes between 2 integers. 

Given 2 integers A ¡Ü B < 105 what¡¯s the number of primes in range from A to B inclusive. 

Note: A prime number is a positive integer greater than 1 and is divisible by 1 and itself only. For N to be prime it is enough to test the divisibility 
of numbers less than or equal to square root of N.
Input

As many as 1000 lines, each line contains 2 integers A and B separated by a space. Input is terminated when A = B = -1 (Do not process this line).
Output

For every line in input ¨C except for the last line where A = B = -1 - print the number of prime numbers between A and B inclusive.
Sample Input

0 9999
1 5
-1 -1
Sample Output

1229
3
Source

Seventh ACM Egyptian National Programming Contest
*/

#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
bool notprime[100005] = {0};

void primejudge()
{
	notprime[0] = 1;
	notprime[1] = 1;
	for(int i = 2; i <= 100000; ++i)
	{
		if(notprime[i]) continue;
		for(int j = 2; j <= sqrt(float(i)); ++j)
		{
			if(i % j == 0)
			{
				notprime[i] = 1;
			}
		}
		for(int k = 2; k * i <= 100000; ++k)
		{
			notprime[i*k] = 1;
		}
	}
}

int prime_count(int x, int y)
{
	int s = 0;
	for(int i = x; i <= y; ++i)
	{
		if(!notprime[i]) ++s;
	}
	return s;
}

int main()
{
	primejudge();
	int a = 0, b = 0;
	while(true)
	{
		scanf("%d%d", &a, &b);
		if(a == -1 && b == -1) break;
		if(a < 1) a = 1;
		if(b < 1) b = 1;
		printf("%d\n", prime_count(a, b));
	}
	return 0;
}

转载于:https://my.oschina.net/locusxt/blog/145878

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值