POJ2247 Humble Numbers

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>

using namespace std;
int num[5845];
void f()
{
    int i, j, k, l, temp;
    i = j = k = l = 2;
    memset(num, 0, sizeof(num));
    num[0] = num[1] = 1;
    int num1, num2, num3, num4;
    for (int m = 2; m <= 5842; m++)
    {
        num1 = num[i-1] * 2;
        num2 = num[j-1] * 3;
        num3 = num[k-1] * 5;
        num4 = num[l-1] * 7;
        temp = min(min(num1, num2), min(num3, num4));
        num[m] = temp;
        if (temp == num1)   i++;
        if (temp == num2)   j++;
        if (temp == num3)   k++;
        if (temp == num4)   l++;
    }
}
int main()
{
    int n;
    f();
    while (cin >> n)
    {
        if (n == 0)
            break;
        if (n % 10 == 1 && n % 100 != 11)
            cout << "The " << n << "st humble number is " << num[n] << '.' << endl;
        else if (n % 10 == 2 && n % 100 != 12)
            cout << "The " << n << "nd humble number is " << num[n] << '.' << endl;
        else if (n % 10 == 3 && n % 100 != 13)
            cout << "The " << n << "rd humble number is " << num[n] << '.' << endl;
        else
            cout << "The " << n << "th humble number is " << num[n] << '.' << endl;
    }
    return 0;
}
 
 
附上看不懂的一个 
 

//Problem: 2247		User: himdd
//Memory: 188K		Time: 16MS
//Language: C++		Result: Accepted
//Source Code
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int ans[6000]={1,1};
int prime[4]={2,3,5,7};
int a[4];
void getans()
{
    for(int c=2;c<=5842;c++)
    {
        for(int i=0;i<4;i++)
        {
            while(prime[i]*ans[a[i]]<=ans[c-1])a[i]++;
        }
        int min=2000000001;
        for(int i=0;i<4;i++)
        {
            if(prime[i]*ans[a[i]]<min)
                min = prime[i]*ans[a[i]];
        }
        ans[c]=min;
    }
}
int main()
{
    int n;
    getans();
    while(scanf("%d",&n),n)
    {
        if(n%10==1 && n%100 !=11)
            printf("The %dst humble number is %d.\n",n,ans[n]);
        else if( n%10 == 2 && n%100 !=12)
            printf("The %dnd humble number is %d.\n",n,ans[n]);
        else if( n%10 == 3 && n%100 !=13 )
            printf("The %drd humble number is %d.\n",n,ans[n]);
        else
            printf("The %dth humble number is %d.\n",n,ans[n]);
    }
    return 0;
}

一个humble数和{2,3,5,7}的积一定是一个humble,那么找出他们其中最小的作为新的humble。
为了加快搜索过程,可以使用一个素数集大小的数组记录这个素数与某个humble的积<=当前最大的humble,这样可以过滤掉小的数,而且这个最大的humble和这个素数的乘积就有可能是最小的未生成的humble,比较每个素数能产生的最小的 humble,选一个最小的作为新的humble。

你可能感兴趣的:(C++,c,user,include,DST,Numbers)