uva 11408 Count DePrimes 求素数变式

A number is called a DePrime if the sum of its prime factors is a prime number.
Given a and b count the number of DePrimes xi such that a ≤ xi ≤ b.
Input
Each line contains a and b in the format ‘a b’. 2 ≤ a ≤ 5000000. a ≤ b ≤ 5000000.
Input is terminated by a line containing ‘0’.
Output
Each line should contain the number of DePrimes for the corresponding test case.
Explanation:
In Test Case 2, take 10. Its Prime Factors are 2 and 5. Sum of Prime Factors is 7, which is a prime.
So, 10 is a DePrime.

Sample Input
2 5
10 21
100 120
0
Sample Output
4
9
9

给定a,b,求a-b之间质因子和为质数的数的个数
思路:求素数打表的同时记录每个数的质因子和

求素数打表:

void init()
{
    int num=1;
    memset(prime,0,sizeof(prime));
    memset(visit,false,sizeof(visit));
    for(int i=2;i//快速求素数
    {
        if(!visit[i])
            prime[num++]=i;
        for(int j=1;j<=num&&i*prime[j]true;
            if(i%prime[j]==0)
                break;
        }
    }
    visit[1]=true;
  }

ac代码:


#include 
#include 
using namespace std;
const int Maxn=5000005;
int prime[Maxn];
bool mark[Maxn];
int n[Maxn];
int sum[Maxn];//存储第i个数的质因子和
void init()
{
    int i,j,num=1;
    n[0]=0;
    n[1]=0;
    memset(prime,0,sizeof(prime));
    memset(mark,true,sizeof(mark));
    for(i=2;iif(mark[i])
        {
            prime[num++]=i;
            sum[i]=i;
        }
        for(j=1;jif(i*prime[j]>Maxn)
                break;
            mark[i*prime[j]]=false;
            if(i%prime[j]==0)
            {
                sum[i*prime[j]]=sum[i];
                break;
            }
            sum[i*prime[j]]=sum[i]+prime[j];
        }
        if(mark[sum[i]])
            n[i]=n[i-1]+1;
        else
            n[i]=n[i-1];
    }
}
int main()
{
    int a,b;
    init();

    while(cin>>a)
    {
        if(a==0)
            break;
        cin>>b;
        cout<1]<return 0;
}

你可能感兴趣的:(c++,算法训练)