1. 程式人生 > >(POJ3292)Semi-prime H-numbers

(POJ3292)Semi-prime H-numbers

Semi-prime H-numbers
Description

This problem is based on an exercise of David Hilbert, who pedagogically suggested that one study the theory of 4n+1 numbers. Here, we do only a bit of that.

An H-number is a positive number which is one more than a multiple of four: 1, 5, 9, 13, 17, 21,… are the H-numbers. For this problem we pretend that these are the only numbers. The H-numbers are closed under multiplication.

As with regular integers, we partition the H-numbers into units, H-primes, and H-composites. 1 is the only unit. An H-number h is H-prime if it is not the unit, and is the product of two H-numbers in only one way: 1 × h. The rest of the numbers are H-composite.

For examples, the first few H-composites are: 5 × 5 = 25, 5 × 9 = 45, 5 × 13 = 65, 9 × 9 = 81, 5 × 17 = 85.

Your task is to count the number of H-semi-primes. An H-semi-prime is an H-number which is the product of exactly two H-primes. The two H-primes may be equal or different. In the example above, all five numbers are H-semi-primes. 125 = 5 × 5 × 5 is not an H-semi-prime, because it’s the product of three H-primes.

Input

Each line of input contains an H-number ≤ 1,000,001. The last line of input contains 0 and this line should not be processed.

Output

For each inputted H-number h, print a line stating h and the number of H-semi-primes between 1 and h inclusive, separated by one space in the format shown in the sample.

Sample Input

21
85
789
0
Sample Output

21 0
85 5
789 62
Source

Waterloo Local Contest, 2006.9.30

題意:
H-number是4*n+1這樣的數,如1,5,9,13… 。
H-primes是這樣一個H-number:它只能唯一分解成1*它本身,而不能表示為其他兩個H-number的乘積。
一個H-semi-prime是一個這樣的H-number:它正好能表示成兩個H-primes的乘積(除了1*它本身),這種表示法可以不唯一,但它不能表示為3個或者以上H-primes的乘積。
現在給出一個數n,要求區間[1,n]內有多少個H-semi-prime。

分析:
本題就是一個素數篩法的變形。原先我們求素數時是在1,2,3,。。。n中求解,不過現在變成了在1,5,9,。。。,4n+1裡面求解。
所有照著素數篩法的演算法寫就可以了。

素數篩法:

int getPrime()
{
    memset(prime,0,sizeof(prime));
    for(int i=2;i<=maxn;i++)
    {
        if(!prime[i]) prime[++prime[0]] = i;
        for(int j=1;j<=prime[0] && prime[j]<=maxn/i;j++)
        {
            prime[prime[j]*i] = 1;
            if(i % prime[j] == 0) break;
        }
    }
    return prime[0];
}

AC程式碼:

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

const int maxn = 1000010;
int ans[maxn],h;
int hprime[maxn];

void h_se_primes()
{
    memset(hprime,0,sizeof(hprime));
    for(int i=5;i<=maxn;i+=4)
    {
        for(int j=5;j<=i;j+=4)
        {
            if(i * j > maxn) break;
            if(!hprime[i] && !hprime[j]) hprime[i*j] = 1;
            else hprime[i*j] = -1;
        }
    }

    //
    memset(ans,0,sizeof(ans));
    for(int i=1;i<=maxn;i++)
    {
        ans[i] = ans[i-1];
        if(hprime[i]==1) ans[i]++;
    }
}

int main()
{
    h_se_primes();
    while(scanf("%d",&h)!=EOF && h)
    {
        printf("%d %d\n",h,ans[h]);
    }
    return 0;
}