Spoj PRIME1 - Prime Generator

Posted lovewhy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spoj PRIME1 - Prime Generator相关的知识,希望对你有一定的参考价值。

题意翻译

求给定的两个数之间的素数

Translated by @kaiming

题目描述

Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!

输入输出格式

输入格式:

 

The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.

 

输出格式:

 

For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.

 

输入输出样例

输入样例#1: 复制
2
1 10
3 5
输出样例#1: 复制
2
3
5
7

3
5

说明

Warning: large Input/Output data, be careful with certain languages (though most should be OK if the algorithm is well designed)
Information

After cluster change, please consider PRINT as a more challenging problem.

 

//Pro: Spoj PRIME1 - Prime Generator
//求给定的两个数之间的素数 

#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
using namespace std;

const long long N=40000;

long long T;
long long cnt;
long long prime[N+1];
bool flag[N+1];

void init()
{
    flag[1]=1;
    long long tmp;
    for(long long i=2;i<=N;++i)
    {
        if(!flag[i])
            prime[++cnt]=i;
        for(long long j=1;j<=cnt&&(tmp=i*prime[j])<=N;++j)
        {
            flag[tmp]=1;
            if(i%prime[j]==0)
                break;
        }
    }
}


long long l,r;
bool Flag;
int main()
{
    init();
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&l,&r);
        for(;l<=r;++l)
        {
            if(l<=N)
            {
                if(!flag[l])
                {
                    printf("%d
",l);
                    continue;
                }
            }
            else
            {
                Flag=0;
                for(long long j=1;prime[j]<=sqrt(l)&& !Flag && j<=cnt;++j)
                {
                    if(l%prime[j]==0)
                        Flag=1;
                }
                if(!Flag)
                    printf("%d
",l);
            }
        }
        puts("");
    }
    return 0;
}

 


以上是关于Spoj PRIME1 - Prime Generator的主要内容,如果未能解决你的问题,请参考以下文章

ruby prime1.rb

在m和n之间生成素数[重复]

SPOJ Prime or Not - 快速乘 - 快速幂

SPOJ PON - Prime or Not

SPOJ CZ_PROB1 - Summing to a Square Prime

bzoj 2820 / SPOJ PGCD 莫比乌斯反演